Posts

Showing posts from December, 2007

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)  ...