Best way to check if the data table has a null value

What is the best way to check if a data table has a null value?

In most cases, in our scenario, one column will have all zero values.

(This datatable is returned by a third-party application - we are trying to put valiadation before our application processes the data table)

+61
null c # validation datatable
Jan 05 2018-11-11T00:
source share
3 answers

Try comparing the value of the column with the value of DBNull.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 } 

Additional DBNull Class Information




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<DataRow>().Any(r => r.IsNull(column))) return true; } return false; } 

which will let you write this:

 table.HasNull(); 
+130
Jan 05 2018-11-11T00:
source share
 foreach(DataRow row in dataTable.Rows) { if(row.IsNull("myColumn")) throw new Exception("Empty value!") } 
+18
Jan 05 2018-11-11T00:
source share

You can quote rows and columns by checking for zeros, keeping track of whether there is a zero with bool, and then checking it after scrolling through the table and process it.

 //your DataTable, replace with table get code DataTable table = new DataTable(); bool tableHasNull = false; foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { //test for null here if (row[col] == DBNull.Value) { tableHasNull = true; } } } if (tableHasNull) { //handle null in table } 



You can also exit the foreach loop with a break statement, for example.

 //test for null here if (row[col] == DBNull.Value) { tableHasNull = true; break; } 

To save the loop in the rest of the table.

+8
Jan 05 2018-11-11T00:
source share



All Articles