How to use DataSet instead of DataTable in C#

戏子无情 提交于 2019-12-13 04:39:44

问题


I have the following template which fills my UL with data received from a DataTable:

DataTable dt = getData(); //Insert your datasource here

    foreach(DataRow row in dt.Rows){
        HtmlGenericControl li = new HtmlGenericControl("li");
        li.Attributes.Add("data-trait-id", row["TraitID"].ToString());

        HtmlAnchor a = new HtmlAnchor();
        a.Attributes.Add("data-trait-id", row["TraitID"].ToString());

        HtmlGenericControl span1 = new HtmlGenericControl("span");
        span1.Attributes.Add("class", "name");
        span1.InnerText = row["Name"].ToString();
        a.Controls.Add(span1);

        HtmlGenericControl span2 = new HtmlGenericControl("span");
        span2.Attributes.Add("class", "count");
        span2.InnerText = row["Count"].ToString();
        a.Controls.Add(span2);

        li.Controls.Add(a);
        ulSpecialty_selector.Controls.Add(li);
    }

But in my page I am using DataSet to get the columns from a SQL query:

protected void Page_Load(object sender, EventArgs e)
    {
        using (OleDbConnection connection = new OleDbConnection("Provider=MSDataShape;Data Provider=SQLOLEDB;" + "Data Source=svr;Initial Catalog=db;User ID=zh;Password=zha")) {
            OleDbDataAdapter adapter = new OleDbDataAdapter("SHAPE {SELECT * FROM [db].[dbo].[BookingTable]} ", connection);

            DataSet dsLocation = new DataSet();
            adapter.Fill(dsLocation, "Location");
        }
    }

How can I use the first block of code to work with the second block of code so I can generate the LI inside the UL?

I am looking to emulate the following:

<ul class="ulLocation" id="ulLocation2_selector" runat="server">
    <li class="liSubLocation active" data-trait-id="9">
        <a href="/locations/new-york/neighborhoods?tags[]=12&amp;tags[]=66" class="premote trait-link large btn" data-trait-id="9">
        <span class="check"><i class="icon icon-ok"></i></span>
        <span class="name">New Rochelle</span>
        <span class="count">6</span>
            </a>
    </li>
</ul>

回答1:


You can easily convert DataTable to DataSet or vice-versa DataTable from DataSet

//Assuming oDS is my DataSet
DataTable oDt =  oDS.Tables[0];// If you know name of datatable you may use oDS.Tables["name"]

DataSet from DataTable

//Assuming oDT is your DataTable
DataSet oDs = new DataSet();
oDs.Tables.Add(oDT);



回答2:


Assuming that you are returning a dataset from GetData(), you can change the following:

DataSet ds = getData();
DataTable dt;
if (ds.Tables.Count > 0)
{
    dt = ds.Tables[0];
}

foreach(DataRow row in dt.Rows){

...



来源:https://stackoverflow.com/questions/23565614/how-to-use-dataset-instead-of-datatable-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!