Cannot use SqlCeDataReader.HasRow
[EDIT] I changed my开发者_StackOverflow社区 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();
}
Get rid of the HasRows
if statement. You can loop through readers by doing while (rdr.Read())
. It will return false (skip while) if no records are returned. (At least with SqlDataReaders)
As the message says, HasRows is not supported. You should be fine skipping that check. Also using using
is recommended in these situations.
using(SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
dg2.Items.Add(new DataItem2() { FooName = (string)rdr["FooName"] });
}
}
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.
精彩评论