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

前端 未结 6 1808
别跟我提以往
别跟我提以往 2020-12-09 15:45

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

Now I connect to the database using an ODBC connection and get the value into a DataTable in .n

相关标签:
6条回答
  • 2020-12-09 15:56

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

    Here's an example:

       if (! DBNull.Value.Equals(row[fieldName])) 
       {
          //not null
       }
       else
       {
          //null
       }
    
    0 讨论(0)
  • 2020-12-09 15:56

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

    Example using the column index:

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

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


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

    0 讨论(0)
  • 2020-12-09 16:11

    row.IsNull("column")

    0 讨论(0)
  • 2020-12-09 16:12
    System.Convert.IsDbNull][1](table.rows[0][0]);
    

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

    0 讨论(0)
  • 2020-12-09 16:12

    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
    }
    
    0 讨论(0)
  • 2020-12-09 16:14

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

       using( var idr = connection, SP.......)
       {
           while(idr.read())
           {
              if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
              //do something
           }
       }
    
    0 讨论(0)
提交回复
热议问题