How to check if Datarow value is null

2019-01-23 13:42发布

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{}

2条回答
叛逆
2楼-- · 2019-01-23 13:51

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"];
}
查看更多
可以哭但决不认输i
3楼-- · 2019-01-23 14:12

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");
查看更多
登录 后发表回答