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


Grammarly

More than 40 Lakhs Students and Professionals use Grammarly for their spell and grammar checks. You can register and try for free.

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;
}

Grammarly

More than 40 Lakhs Students and Professionals use Grammarly for their spell and grammar checks. You can register and try for free.
%d bloggers like this: