无法使用 SqlCeDataReader.HasRow
[编辑] 我根据你的答案更改了我的代码。但现在我收到另一个错误:
IndexOutOfRangeException was Handled.
我有一个空表开始。奇怪..
下面是我的代码。有什么想法吗?
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
dg2.Items.Add(new DataItem2() { FooName = (string)rdr["FooName"],});
}
rdr.Close();
}
[编辑 - 第二次] 我编辑了我的代码并使用 rdr[0] 而不是 rdr["String"],我得到了一个不同的错误
“索引超出了数组的范围。”
天啊,这让我抓狂。我从绝对空的行开始,我不知道这些奇怪的错误是如何弹出的
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
dg2.Items.Add(new DataItem2() { FooName = (string)rdr[0],});
}
rdr.Close();
}
[EDIT]
I changed my code according to the your answers. But now I get another error:
IndexOutOfRangeException was Handled.
I have an empty table to begin with. Weird..
Below is my code. Any idea?
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
dg2.Items.Add(new DataItem2() { FooName = (string)rdr["FooName"],});
}
rdr.Close();
}
[EDIT - 2nd]
I edited my code and use rdr[0] instead of rdr["String"], I get a different error
"Index was outside the bounds of the array."
omg, this is driving my nuts. I have absolutely empty rows to start with and I have no idea how these strange errors pop up
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
dg2.Items.Add(new DataItem2() { FooName = (string)rdr[0],});
}
rdr.Close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
去掉
HasRows
if 语句。您可以通过执行while (rdr.Read())
循环遍历读取器。如果没有返回记录,则返回 false(skip while)。 (至少对于 SqlDataReaders)Get rid of the
HasRows
if statement. You can loop through readers by doingwhile (rdr.Read())
. It will return false (skip while) if no records are returned. (At least with SqlDataReaders)正如消息所述,不支持 HasRows。你应该可以跳过该检查。在这些情况下,还建议使用
using
。As the message says, HasRows is not supported. You should be fine skipping that check. Also using
using
is recommended in these situations.另外,如果您使用 SqlCeDataReader 返回一个聚合值(例如 Max()),它似乎不允许您检查 null。 [如果没有行,则会发生这种情况]
IsDbNull(0) 引发了错误,因此我的解决方案只是尝试读取该值并捕获将引发的 System.Data.SqlTypes.SqlNullValueException 。
Also, if you use SqlCeDataReader to return an aggregate value such as Max() it doesn't seem to allow you to check for a null. [This occurs if there are no rows]
IsDbNull(0) raised an error, so my solution was just to try to read the value and Catch the System.Data.SqlTypes.SqlNullValueException that will be raised.