Invalid attempt to read when no data is present.

A short one.

You are reading data from a data reader, and sometimes you hit:

Invalid attempt to read when no data is present.

It may seem obvious, but there have been occasions where this error is reported.

When checking the code sample below, it is obvious what is going on, but if you have, for example, a framework

that passes a reader around, or in some way have the value reading logic separated from the row reading logic,

then you may encounter this.

Basically you are trying to read a value from a row that does not exist.

This usually happens when the DataReader has moved beyond the last record and an attempt is made to read a row value.

So, using the trusty Northwind database, run this code and you will understand why it fails with the error above.

        static void Main(string[] args)

        {

            string cs = @"Server=<your server>;Integrated Security=SSPI;Initial catalog=Northwind";

            using (SqlConnection conn = new SqlConnection(cs))

            {

                try

                {

                    conn.Open();

                    SqlCommand cmd = conn.CreateCommand();

                    cmd.CommandText = "select * from Shippers";

                    SqlDataReader dr = cmd.ExecuteReader();

                    while (dr.Read())

                    {

                        object o = dr.GetValue(0);

                        Console.WriteLine(o.ToString());

                    }

                    // The dr.Read has moved to the next record (but returned false of course, otherwise we'd still be in the while loop),

                    // which does not exist, so now there is an attempt to read that is not present.

                    object fail = dr.GetValue(0);

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex);

                }

            }

        }

This may happen when you are operating on the assumption that there is a fixed number of records in a table, but that the number is incorrect, say, a row has been deleted.

For example, the Shippers table contains 4 rows, but the assumption is that there is 5:

                    for (int i = 0; i < 5; i++)

                    {

                        dr.Read();

                        object o = dr.GetValue(0);

                        Console.WriteLine(o.ToString());

                    }