检查列是否返回空值的最佳方法(从数据库到.net应用程序)

sol*_*man 30 .net c# datatable null datetime

我有一个带有DateTime列的表,该列可以具有NULL值

现在我使用ODBC连接连接到数据库,并将值传入.net/c#中的DataTable.

我可以通过去检查它是否为NULL

if(String.IsNullOrEmpty(table.rows[0][0].ToString())
{
     //Whatever I want to do
}
Run Code Online (Sandbox Code Playgroud)

String.IsNullOrEmpty是检查空值的正确方法.

jba*_*all 81

在对象上使用DBNull.Value.Equals而不将其转换为字符串.

这是一个例子:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }
Run Code Online (Sandbox Code Playgroud)


Mar*_*nze 10

只需使用DataRow.IsNull.它已覆盖接受列索引,列名称DataColumn对象作为参数.

使用列索引的示例:

if (table.rows[0].IsNull(0))
{
    //Whatever I want to do
}
Run Code Online (Sandbox Code Playgroud)

虽然这个函数被称为IsNull真正的比较DbNull(这正是你需要的).


如果我想检查DbNull但我没有DataRow怎么办?使用Convert.IsDBNull.