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
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
Return (DbReader.GetOrdinal(ColumnName) > -1)
End Function
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.
Post a Comment