Tuesday, 21 December 2010

Get the value in datarow by column index in ADO.NET

Question:
Working with datasets has always been problematic.
For each property access you have to test again and again.
This is a case for a utility method and since .Net 2 an application of extension methods.



Answer:
We extend the data row with a generic extension method that is doing all the testing for us.

Here is the code:

Get the value of the n'th column in the datarow.
If index is out of range or value null returns false and outs default value for type
public static bool TryGetValue<t>(this DataRow dr, int idxCol, out T val)
{
    bool result = false;
    val = default(T);

    if ((idxCol >= 0) && dr[idxCol] != System.DBNull.Value)
    {
        val = (T)dr[idxCol];
        result = true;
    }

    return result;
}

Here is a version that gets the value as return.
If the index is out of range or value is null then it returns the default value for type.
public static T GetValueOrDefault<t>(this DataRow dr, int idxCol)
{
    T result;
    dr.TryGetValue<t>(idxCol, out result);
    return result;
}
And now you can use it like this:

int age = myRow.GetValueOrDefault<int>(2);

No comments: