【问题标题】:Filling a DataTable based on row values in a DataSet根据 DataSet 中的行值填充 DataTable
【发布时间】:2012-02-05 23:16:24
【问题描述】:

我想在网站的首页上显示一些新闻帖子。新闻有不同的类别,但存储在同一个mysql数据库中。所有新闻项目都加载到数据集中,但我只想从那里提取一些特定新闻并将它们显示在 ListView 控件中。

目前,我正在使用在数据集上使用 foreach 循环并在后面的代码中使用 html 格式化结果的解决方案。它可以工作,但我希望所有 html 格式都在 aspx 文件中完成,因此我正在寻找更好的解决方案。

        DataSet articles = db.loadAllArticles();
        foreach (DataRow item in articles.Tables["articles"].Select("category = 1"))
        {
            result += "<h1 class='headline'>" + item["headline"] + "</h1><h2 class='introduction'>" + item["introduction"] + "</h2><p class='content'>" + item["content"] + "</p><p class='authorAndDate'>" + item["author"] + " " + item["datePosted"].ToString().Substring(0,10) + "</p><br/>";                  
        }
        lblDisplay.Text = result;

我希望我能做的只是这样的事情:

DataSet articles = db.loadAllArticles();
ListView1.DataSource = articles.Tables["articles"].Select("category = 1");
ListView1.DataBind();

但是 ListView 控件对尝试将 DataRow 绑定到它或其他东西不太高兴。 我能想到的最佳解决方法是在“文章”数据集中创建一个新表,其中仅包含所选类别的文章,因此如下所示:

DataSet articles = db.loadAllArticles();
articles.Tables.Add("frontPageArticles");
articles.Tables["frontPageArticles"] = ???

然后这就是它停止的地方。如何用列值为 x 的其他数据表中的行填充新数据表?

-埃里克。

【问题讨论】:

    标签: c# asp.net datatable dataset


    【解决方案1】:

    您应该考虑将 ListView 绑定到 DataView,它是可过滤和可排序的。

    【讨论】:

    • 谢谢,工作就像一个魅力。我的解决方案(对于那些将来遇到类似问题的人):DataSetarticles = db.loadAllArticles(); DataView frontPageArticles = new DataView(articles.Tables["articles"]); frontPageArticles.RowFilter = "类别 = 1"; ListView1.DataSource = frontPageArticles; ListView1.DataBind();
    【解决方案2】:

    您可以使用中继器、数据列表等控件设计您的 Web 表单,并将这些控件绑定到代码隐藏上的数据表。

    可以找到一个例子here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2010-09-05
      • 2013-03-05
      • 1970-01-01
      相关资源
      最近更新 更多