Rod
Rod

Reputation: 15457

Check DataTable if a column exists and if it's null

Environment: .Net Framework 3.5

I have a DataTable that can bring back variable amount of columns for the same table in a database and I'm checking if the column exists and if it does is it null like the following:

This is when I'm mapping a DataTable to an entity

Status = dt.Columns["Status"] != null ? row["Status"] == DBNull.Value ? 0 : Convert.ToInt16(row["Status"]) : 0,

Is this pretty standard or might I be missing any other case? Other more concise ways?

Upvotes: 0

Views: 699

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Everything is better with Doodles extension methods:

public static class DataTableExtensions
{
    public static T GetValueOrDefault<T>(this DataRow row, string columnName)
    {
        return row.GetValueOrDefault<T>(columnName, default(T));
    }

    public static T GetValueOrDefault<T>(this DataRow row, string columnName, T defaultValue)
    {
        return row.Table.Columns[ColumnName] != null && 
               row[columnName] != DbNull.Value && 
               row[columnName] is T ? (T)row[columnName] : defaultValue;
    }
}

Usage:

var Status = row.GetValueOrDefault<Int16>("status");

or

var Status = row.GetValueOrDefault<Int16>("status", -1);

Upvotes: 2

Related Questions