【问题标题】:How to use DataSet instead of DataTable in C#如何在 C# 中使用 DataSet 而不是 DataTable
【发布时间】:2014-05-09 13:16:06
【问题描述】:

我有以下模板,它用从 DataTable 接收到的数据填充我的 UL

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);
    }

但在我的页面中,我使用 DataSet 从 SQL 查询中获取列:

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");
        }
    }

如何使用第一个代码块来处理第二个代码块,以便在UL 中生成LI

我希望模仿以下内容:

<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>

【问题讨论】:

  • 我假设您知道 DataSets 只是 DataTables 的集合,并且您基本上可以像在第一个代码块中使用它一样通过将 DataTable 加载到DataSet 并引用 DataSet 内的第一个索引表。像这样.. DataSet dsLocation = new DataSet(); dsLocation.Tables[0]
  • DataTable dt = dsLocation.Tables[0]

标签: c# sql sql-server htmlgenericcontrol


【解决方案1】:

您可以轻松地将 DataTable 转换为 DataSet,反之亦然 数据集中的数据表

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

数据表中的数据集

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

【讨论】:

  • 谢谢。我让它工作,但我怎样才能从我的问题中模拟 LI?因为它似乎与 BulledtedList 我不能有孩子
【解决方案2】:

假设您从 GetData() 返回一个数据集,您可以更改以下内容:

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

foreach(DataRow row in dt.Rows){

...

【讨论】:

  • @Sikni8 您也许可以使用 ASPX 中继器控件。我自己从来没有用过它,它可能对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2011-03-25
  • 2023-03-03
  • 2011-11-25
  • 2012-09-12
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多