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();
}
}
Asked
Active
Viewed 193 times
-1

David Pilkington
- 13,528
- 3
- 41
- 73
-
Check this link https://stackoverflow.com/questions/18961938/populate-data-table-from-data-reader – A.M. Patel May 27 '19 at 12:22
1 Answers
0
So when debugging your snippet, you should be able to see, that there is data read by the dr.Read()
.
And while reading your DataReader dr.Read()
will consume all incoming data rows one-by-one. And within your while
-loop you will operate with the received data.
// Get data row by row
while (dr.Read())
{
// Displays the current "Status" content in your textbox
textBox1.Text = (dr["Status"].ToString());
}
And when it now comes to creating your DataTable
with Load()
. The reader has just finished reading and hasn't any row left to read.
dt.Load(dr);
So your displayed DataGrid will be empty.
As a hint:
I recommend wrapping your data reader in a using block like
using(SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
//Processing
}
// or
dt.Load(dr);
}
This will close and dispose your data reader. You may take a look at Is it necessary to manually close and dispose of SqlDataReader?

Martin Backasch
- 1,829
- 3
- 20
- 30