Winforms 中的 DatagridView ,SqlDataReader 是否在循环结束时自动关闭?
int a ;
SqlCommand cmd = new SqlCommand (" Select * From items order by ItemID ", conn );
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
a = reader.GetInt32(0);
if (reader.HasRows == false)
{
dataGridView1.Visible = false;
}
else
{
dataGridView1.Visible = true;
DataTable dt = null;
dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
if (reader.IsClosed == true)
{
break;
}
}
我想问读者是否自动关闭,因为这里没有使用 reader.Close() 但它仍然关闭?另外,在我的项目表中,我的第一条记录为
ItemId | ItemName
1 Bag
2 Laptop
8 Weighing Machine
但是,当此数据显示在 datagridview 中时,第 1 行(即项目名称“BAG”)不会显示。为什么会这样?
int a ;
SqlCommand cmd = new SqlCommand (" Select * From items order by ItemID ", conn );
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
a = reader.GetInt32(0);
if (reader.HasRows == false)
{
dataGridView1.Visible = false;
}
else
{
dataGridView1.Visible = true;
DataTable dt = null;
dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
if (reader.IsClosed == true)
{
break;
}
}
I want to ask that is the reader closed automatically, because here am not using reader.Close() and still it is closed? also , in my items table i have the first record as
ItemId | ItemName
1 Bag
2 Laptop
8 Weighing Machine
But, when this data is displayed in the datagridview then the row 1 , that is, the itemname "BAG" is not displayed. why so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过调用 Read(),您已经“声明”了第一行(因此 Bag 没有显示 - 因为您没有对它执行任何操作);然而,
dt.Load
也将执行while(reader.Read())
。我希望你想要(注意我没有在这里调用Read
,并且没有while
循环):它退出的原因是一旦你调用了
Load
您已经读取了所有数据,因此没有其他内容可读取。老实说,我不知道到达 TDS 流的末尾是否会隐式关闭阅读器,但您应该使用:By calling
Read()
, you have already "claimed" the first row (hence why Bag isn't showing - because you aren't doing anything with it); and yetdt.Load
is also going to do awhile(reader.Read())
. I expect you want (note I'm not callingRead
here, and have nowhile
loop):The reason it is exiting is that once you've called
Load
you've already read all the data, so there is nothing else to read. I honestly don't know whether getting to the end of the TDS stream implicitly closes the reader, but you should be using:您将读取器加载到 DataTable 中,因此不需要 while(reader.Read()) 循环。
第一条记录未显示,因为 reader.Read() 已获取第一条记录,而 dt.Load() 从第二条记录开始。
You are loading the reader into the DataTable so the while(reader.Read()) loop is not required.
The first record is not displaying because reader.Read() has taken the first record and dt.Load() is starting from the second record.
即使这对我来说也很好用
Even this too works fine for me