How to Determine if a Column Exists in a DataReader

I recently had to work on something which required me to query a database, open the results in a DataReader, and check for the existence of a particular column. While the DataReader doesn't have a method to do this, with just a few steps I was able to accomplish this task. Here's how.

First, the DataReader has a method named GetSchemaTable(), which returns a DataTable consisting of information regarding the data contained in the DataReader. The first column in this DataTable is named ColumnName, and its value is (obviously) the name of the column.

Knowing this, we can loop through the rows in the DataTable, checking the ColumnName column for a value that equals the name of the column we're looking for. To this end, I wrote a static method in one of my classes which takes the DataReader and the name of the column being sought:


(C#)
public static bool HasColumn(DbDataReader Reader, string ColumnName)
{
   foreach (DataRow row in Reader.GetSchemaTable().Rows)
   {
      if (row["ColumnName"].ToString().ToUpper() == FieldName.ToUpper())
      return true;
   }

   //Still here? Column not found.
   return false;
}

(VB.NET)
Public Shared Function HasColumn(Reader As DbDataReader, ColumnName As String) as Boolean
   For Each DataRow row in Reader.GetSchemaTable().Rows
   
      If row("ColumnName").ToString().ToUpper() = FieldName.ToUpper() Then Return True

   Next

   'Still here? Column not found.
   Return False
End Function


Comments

Anonymous said…
Public Function ColumnExists(ByRef DbReader As System.Data.Common.DbDataReader, ByVal ColumnName As String) As Boolean
Return (DbReader.GetOrdinal(ColumnName) > -1)
End Function
Alan said…
Hi Anonymous

Yes, that is a much better way to do it! I was unaware of GetOrdinal() at the time I wrote this original post almost 5 years ago.

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

How To Mock Out Child Components In Unit Tests of Angular 2 Code