【问题标题】:DataGridView not showing data when i use while loop or if statement当我使用 while 循环或 if 语句时,DataGridView 不显示数据
【发布时间】:2019-05-27 12:09:15
【问题描述】:
private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("select * from AccountTbl where EmployeeCode=" + comboBox1.Text, con);
            con.Open();
            DataTable dt = new DataTable();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                textBox1.Text = (dr["Status"].ToString());
            }
            dt.Load(dr);
            dataGridView1.DataSource = dt;
            con.Close();

        }
        catch (Exception ex)
        {

            MessageBox.Show("Enter");
        }
        finally
        {
            con.Close();
        }
    }

【问题讨论】:

标签: c#


【解决方案1】:

所以在调试你的 sn-p 时,你应该能够看到,dr.Read() 读取了数据。

在读取您的 DataReader dr.Read() 时,将一一消耗所有传入的数据行。在您的while-loop 中,您将使用接收到的数据进行操作。

// Get data row by row
while (dr.Read())
{
     // Displays the current "Status" content in your textbox
     textBox1.Text = (dr["Status"].ToString());
}

现在使用Load() 创建您的DataTable。阅读器刚读完,没有任何行可读。

dt.Load(dr);

所以您显示的 DataGrid 将为空。


作为提示:
我建议将您的数据阅读器包装在一个 using 块中,例如

using(SqlDataReader dr = cmd.ExecuteReader())
{
   while (dr.Read())
   {
      //Processing
   }

   // or

   dt.Load(dr);
}

这将关闭并处理您的数据阅读器。 你可以看看 Is it necessary to manually close and dispose of SqlDataReader?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 2017-12-29
    • 2013-06-09
    • 2014-01-21
    • 2015-11-08
    • 2016-01-12
    • 2023-01-02
    • 2015-07-06
    相关资源
    最近更新 更多