How to check if Datarow value is null

2019-01-23 13:38发布

问题:

Tell me please is this is correct way to check NULL in DataRow if need to return a string

 Convert.ToString(row["Int64_id"] ?? "")

Or should be like check with DBNull.Value.

Need to so much more smaller than

if(row["Int64_id"] != DBNull.Value){...}else if{}

回答1:

Check if the data column is not null with DataRow.IsNull(string columnName)

if (!row.IsNull("Int64_id"))
{
  // here you can use it safety
   long someValue = (long)row["Int64_id"];
}


回答2:

We have created an extension class that helps in these kinds of situations.

public static class DataRowExtensions
  {
    public static T FieldOrDefault<T>(this DataRow row, string columnName)
    {
      return row.IsNull(columnName) ? default(T) : row.Field<T>(columnName);
    }
  }

You can use is as follows:

int id = dataRow.FieldOrDefault<int>("Id");