1

I'm dynamically picking a table to select from and there's one field that doesn't exist on all of the tables. Inside my reader, how can I check to see if that field exists in the collection?

I'm using this, but it only determines if it's null...not whether it exists or not:

if (myReader.GetValue(myReader.GetOrdinal("PrePay")) != DBNull.Value)
    myModel.PrePay = myReader.GetBoolean(myReader.GetOrdinal("PrePay"));
Christopher Johnson
  • 2,629
  • 7
  • 39
  • 70
  • 1
    possible duplicate of [Check for column name in a SqlDataReader object](http://stackoverflow.com/questions/373230/check-for-column-name-in-a-sqldatareader-object). Appears to be the big answer to this question – Preet Sangha Sep 01 '11 at 21:04

4 Answers4

0

Have a look at SqlDataReader.GetSchemaTable (assuming myReader is a SqlDataReader).

Philipp Schmid
  • 5,778
  • 5
  • 44
  • 66
0
while(reader.Read())
{
    if(reader.GetOrdinal("FieldName")>=0) //field exists
    {
 ....
    }
}
Icarus
  • 63,293
  • 14
  • 100
  • 115
  • And if the fieldname doesn't exist then you'll get an `IndexOutOfRangeException`, which is presumably what the OP is trying to avoid. – LukeH Sep 01 '11 at 21:09
  • You are right, @LukeH I thought it would return a -1 but reading this: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx I realized that it actually throws an Exception. Christoper Johnson: ignore my answer, I don't know what I'm talking about. – Icarus Sep 01 '11 at 21:12
0
for (int i = 0; i < myReader.FieldCount; i++)
{
    string name = myReader.GetName(i);
    if (string.Equals(name , "PrePay", StringComparison.OrdinalIgnoreCase))
    {
        object value = myReader.GetValue(i);
        if (!Convert.IsDBNull(value))
        {
            myModel.PrePay = (bool)value;
        }
        break;
    }
}

If your reader returns more than one row then you should perform the lookup just once at the beginning and then cache the ordinal to use when iterating through the resultset.

LukeH
  • 263,068
  • 57
  • 365
  • 409
0
While(myReader.Read())
{ 
   MessageBox.Show(myReader.Item("PrePay").toString());
}

Basically, if the value of "PrePay" is null, it's doesn't exist otherwise it's exist.

Sam Casil
  • 938
  • 1
  • 11
  • 16