Search code examples
c#sql-server-cedatareader

Cannot use SqlCeDataReader.HasRow


[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();
}

Solution

  • 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"] });
        }
    }