【问题标题】:SqlDataReader with two tables带有两个表的 SqlDataReader
【发布时间】:2017-05-21 23:54:24
【问题描述】:

我有一个非常简单的代码,可以从两个表中获取数据

  1. 库存
  2. 类别

并在 ASP.NET Web 应用程序的 Page_Load 事件中使用 SqlDataReader 在两个不同的 GridView 控件中显示它们。

我的意思是,SqlDataReader 不应该在读取上一张表(Inventory)的数据后自动遍历到下一张表(Category)吗?而不是使用NextResult(),如果我为下一个网格再次重用rdr对象,即CategoryGridView而不执行NextResult(),我将一无所获(意味着它已经从Inventory?!)

所以简而言之,我的问题是 rdr 从第一个表 (Inventory) 读取后指向 的位置在哪里?

using (SqlConnection con = new SqlConnection(CS))
{
    SqlCommand cmd = new SqlCommand("Select * from tblInventory; Select * from tblCategory", con);
    con.Open();

    using (SqlDataReader rdr = cmd.ExecuteReader())
    {
        InventoryGridView.DataSource = rdr;
        InventoryGridView.DataBind();

        rdr.NextResult();
        CategoryGridView.DataSource = rdr;
        CategoryGridView.DataBind();
    }
}

【问题讨论】:

  • 读完第一个结果集后,读者指向“无处”——越过第一个结果集的末尾。但它不会自动跳转到第二个结果集——你必须使用.NextResult()来实现这个
  • 有趣,实际上混淆来自使用SQLDataReader 读取多行,这需要Read() 在检索值之前。

标签: asp.net sql-server ado.net


【解决方案1】:
connection.Open();
SqlCommand command = new SqlCommand("Select * from tblInventory; Select * from tblCategory", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
    InventoryGridView.DataSource = reader;
    InventoryGridView.DataBind();

    while (reader.NextResult())
    {
        CategoryGridView.DataSource = reader;
        CategoryGridView.DataBind();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多