【问题标题】:DataTable.Load Skips to next result set in multi-result DataReaderDataTable.Load 跳到多结果 DataReader 中的下一个结果集
【发布时间】:2017-05-02 00:04:27
【问题描述】:

我有一个多结果查询,并试图将每个结果绑定到单独的 DataGridView。

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT 1 select 2 select 3 select 4 select 5 select 6"
                                    , con);
    SqlDataReader reader = cmd.ExecuteReader();
    int x = 50;
    int y = 100;
    do
    {
        DataGridView dgv1 = new DataGridView();
        DataTable dt = new DataTable();
        dt.Load(reader);
        dgv1.DataSource = dt;
        dgv1.Left = x;
        dgv1.Top = y;
        dgv1.Height = 60;
        y = y + 70;
        this.Controls.Add(dgv1);
    } while (reader.NextResult());
    reader.Close();
}

如果我不将数据加载到 DataTable 并且不将其绑定到网格,我将得到 6 个结果集,但在上面的代码中,我得到了;y 第一个、第三个和第五个结果集,看起来填充跳过了每个循环中的结果集。

问题是:

  1. 为什么会这样。
  2. 实现此目标的最简单解决方案是什么。

【问题讨论】:

  • DataTable.Load 自动将阅读器推进到下一个结果。

标签: c# sqldatareader


【解决方案1】:

DataTable.Load,前进到下一个结果集,因此您不需要使用 NextResult()。

循环直到阅读器打开。

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT 1 select 2 select 3 select 4 select 5 select 6"
                                    , con);
    SqlDataReader reader = cmd.ExecuteReader();
    int x = 50;
    int y = 100;
    do
    {
        DataGridView dgv1 = new DataGridView();
        DataTable dt = new DataTable();
        dt.Load(reader);
        dgv1.DataSource = dt;
        dgv1.Left = x;
        dgv1.Top = y;
        dgv1.Height = 60;
        y = y + 70;
        this.Controls.Add(dgv1);
    } while (!reader.IsClosed); // here is the change
    reader.Close();
}

【讨论】:

    【解决方案2】:

    使用 read.IsClosed() 的答案没有错,但要注意:

    如果所有 SELECT 中的字段数不一样(同样的数据类型),似乎会出现问题:

    例如1:

        select 2,2 select 1
    

    例如2:

        select 2,2 select 'one', 'one'
    

    (使用 .NET 4.5.2 测试)

    【讨论】:

      猜你喜欢
      • 2011-01-07
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      相关资源
      最近更新 更多