I like to access my DataReader objects via column name. Unfortunately, IDataReader supports getting items via integer indexer.
To overcome this *obstacle*, I've written an extension method I'd like to share. It checks to see whether a column exists and has a value associated with it.
1: public static class IDataReaderExtension
2: {
3: /// <summary>
4: /// Adds the HasValue property to an IDataReader, which checks based on Column name
5: /// </summary>
6: /// <param name="reader">An IDataReader object</param>
7: /// <param name="column">The string column name</param>
8: /// <returns>boolean</returns>
9: public static bool HasValue(this IDataReader reader, string column)
10: {
11: if (reader.GetSchemaTable().Columns.Contains(column))
12: return reader[column] != null || reader[column] != DBNull.Value;
13: else
14: return false;
15: }
16: }
In order to use this method, you can now check:
1: if(reader.HasValue("MY_COLUMN"))
2: {
3: myObject.ColumnInfo = Convert.ToString(reader["MY_COLUMN"]);
4: }
No comments:
Post a Comment