How can i find out if a column exists in a DataReader's results set?
i try:
int columnOrdinal = reader.GetOrdinal("LastName");
columnExists = (columnOrdinal < 0);
but GetOrdinal
throws an exception if the column does not exist. My case is not exceptional. It's the opposite. It's...ceptional.
Note: Not related to my question but, the real reason i want to know if a column exists is because i want to get the ordinal position of a column, without throwing an exception if the column doesn't exist:
int columnOrdinal = reader.GetOrdinal("Lastname");
Note: Not related to my question but, the real reason i want to know if a column exists, because i want to know if the column contains null:
itIsNull = reader.IsDBNull(reader.GetOrdinal("Lastname"));
Unfortunately IsDBNull
only takes an ordinal, and GetOrdinal
throws an exception. So i'm left with:
if (ColumnExists(reader, "Lastname"))
{
itIsNull = reader.IsDBNull(reader.GetOrdinal("Lastname"));
}
else
itIsNull = false;
Note: Not related to my question but, the real reason i want to know if a column exists is because there will be times where the column will not be present in the results set, and i don't want to throw an exception processing database results, since it's not exceptional.