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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2017533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:42:31  来源:igfitidea点击:

Best way to check if column returns a null value (from database to .net application)

c#.netdatetimedatatablenull

提问by soldieraman

I have a table with a DateTime column the column can have NULL values

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

Now I connect to the database using an ODBC connection and get the value into a DataTable in .net / c#.

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

I am able to check it for NULL by going

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

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

Is String.IsNullOrEmpty the correct way to check for null values.

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

采纳答案by jball

Use DBNull.Value.Equalson the object without converting it to a string.

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

Here's an example:

下面是一个例子:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

回答by jspcal

row.IsNull("column")

row.IsNull("列")

回答by Rabbi

Just check for

只需检查

if(table.rows[0][0] == null)
{
     //Whatever I want to do
}

or you could

或者你可以

if(t.Rows[0].IsNull(0))
{
     //Whatever I want to do
}

回答by Marcin Seredynski

System.Convert.IsDbNull][1](table.rows[0][0]);

IIRC, the (table.rows[0][0] == null)won't work, as DbNull.Value != null;

IIRC,这(table.rows[0][0] == null)行不通,因为DbNull.Value != null;

回答by Mariano Desanze

Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn objectas parameters.

只需使用DataRow.IsNull。它具有接受列索引列名DataColumn 对象作为参数的覆盖。

Example using the column index:

使用列索引的示例:

if (table.rows[0].IsNull(0))
{
    //Whatever I want to do
}

And although the function is called IsNullit really compares with DbNull(which is exactly what you need).

尽管调用IsNull了该函数,但它确实与DbNull(这正是您需要的)进行了比较。



What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.

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

回答by priyanka

If we are using EF and reading the database element in while loop then,

如果我们使用 EF 并在 while 循环中读取数据库元素,则

   using( var idr = connection, SP.......)
   {
       while(idr.read())
       {
          if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
          //do something
       }
   }