How to Check for Column Name in SqlDataReader object in C# ?

Do you want to check if a column exists in a SqlDataReader instance in C# ?. One of the simplest solution is to navigate to all the fields within the data reader and check the name of the field using the GetName method as shown below.

How to Check for Column Name in SqlDataReader object in C# ?

public static bool HasColumn(IDataRecord dataReader, string columnName)
{
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
        if (dataReader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }
    return false;
}
%d bloggers like this: