Best way to check if a Data Table has a null value in it

前端 未结 6 1230
感情败类
感情败类 2020-11-27 02:34

what is the best way to check if a Data Table has a null value in it ?

Most of the time in our scenario, one column will have all null values.

(This datatabl

6条回答
  •  有刺的猬
    2020-11-27 03:18

    Try comparing the value of the column to the DBNull.Value value to filter and manage null values in whatever way you see fit.

    foreach(DataRow row in table.Rows)
    {
        object value = row["ColumnName"];
        if (value == DBNull.Value)
            // do something
        else
            // do something else
    }
    

    More information about the DBNull class


    If you want to check if a null value exists in the table you can use this method:

    public static bool HasNull(this DataTable table)
    {
        foreach (DataColumn column in table.Columns)
        {
            if (table.Rows.OfType().Any(r => r.IsNull(column)))
                return true;
        }
    
        return false;
    }
    

    which will let you write this:

    table.HasNull();
    

提交回复
热议问题