ExtensionMethod.NET Home of 820 C#, Visual Basic, F# and Javascript extension methods

GetValue

Get column value bu name from IDataReader.

Source

public static class DataReaderExtension
{
    public static string GetValue(this IDataReader rdr, string columnName)
    {
        return rdr.GetValue<string>(columnName);
    }

    public static T GetValue<T>(this IDataReader rdr, string columnName)
    {
        object data = rdr.GetValue(rdr.GetOrdinal(columnName));
        if (!string.IsNullOrEmpty(data.ToString()))
            return (T)data;

        return default(T);
    }
}

Example

var value = rdr.GetValue<string>(columnName);
var value = rdr.GetValue(columnName);
var value = rdr.GetValue<int>(columnName);
var value = rdr.GetValue<int?>(columnName);

Author: Dumitru Condrea

Submitted on: 10 dec 2010

Language: C#

Type: System.Data.IDataReader

Views: 3756