Search code examples
c#enumerablegetvalue

C# - Trying to add row values to list throws InvalidOperationException


I want to store the values of the columns, i.e. column names, and the row values of a specific row into two seperate lists. Provider and Document are both of List<string>. But since there is a type conflict with Document I'm using var Document, so the compiler accepts it.

The following code works perfectly fine until var Document = Enumerable.Range(0, dr.FieldCount).Select(dr.GetValue).ToList();

OleDbCommand cmd = new OleDbCommand(abfrage, conn);
OleDbDataReader dr;
try
{
    conn.Open();
    dr = cmd.ExecuteReader();
    Provider = Enumerable.Range(0, dr.FieldCount)
                         .Select(dr.GetName)
                         .ToList();
    // Following line will throw exception
    var Document = Enumerable.Range(0, dr.FieldCount)
                             .Select(dr.GetValue)
                             .ToList();
    dr.Close();
    dr.Dispose();
}          
catch (System.InvalidOperationException inv)
{
    MessageBox.Show(inv.Message);
    throw;
}

The first list has the column names correctly stored but the other one throws an InvalidOperationException and says, that there are no values in either the rows or the columns. This is correct for some columns (they're empty). I tested it with another DB-Table where every column/row has a value but I get the same exception here.

What am I doing wrong?

Thanks in advance!

Edit:

Here are two screenshots which show the read values by the reader.

The first one with the column names (values are greyed out, it's sensitive data): first results

The second one with the values of the whole row: read values


Solution

  • You need to call dr.Read() to read the first row from the results.

    Also, your Document in that code is a local variable that gets thrown away. I am guessing you want to assign it to a property of the same name? You will also need to cast the result of dr.GetValue() to a string.

    I think you will want to initialise both Document and Provider and the call AddRange method instead of assigning them to the result.