Reputation: 20046
[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();
}
Upvotes: 0
Views: 1274
Reputation: 1
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.
Upvotes: 0
Reputation: 108957
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"] });
}
}
Upvotes: 0
Reputation: 6524
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)
Upvotes: 1