No data exists for the row/colum when there is data

65 Views Asked by At

i have this code

public static PersonalData[] GetAllPersonalInfo(OleDbCommand cmd)
        {
            cmd.CommandText = "SELECT count(Id) FROM PersonalInfo";
            int count = (int)cmd.ExecuteScalar();
            cmd.CommandText = "SELECT Id From PersonalInfo";
            OleDbDataReader reader = cmd.ExecuteReader();
            PersonalData[] output = new PersonalData[count];
            for (int i = 0; i < count; i++)
            {
                output[i] = GetOnePersonPersonalInfo(reader.GetValue(0), cmd);
                reader.Read();
            }
            reader.Close();
            return output;
        }

which is supposed to go through every entry in a database and get the data and put it in a custom class. but when it reaches the reader.GetValue(0) part it throws an System.InvalidOperationException: 'No data exists for the row/column.' error. i used the debugger to see the values and this is what i found. debugger

there is clearly some data in the reader but it dosn't output it. what am i missing?

1

There are 1 best solutions below

0
Ashish Makhija On

You need to call the reader.Read first. Also instead of applying for a loop, you can simply use a while loop for better code performance. Also, remember to check whether the reader has data or not by using HasRows.

if (!reader.HasRows)
    {
        // No data to read
        reader.Close();
        return new PersonalData[0];
    }

    List<PersonalData> output = new List<PersonalData>();

    while (reader.Read())
    {
        output.Add(GetOnePersonPersonalInfo(reader.GetInt32(0), cmd));
    }