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 datatable is returned by a 3rd party application - we are trying to put a valiadation before our application processes the data-table)
This question is related to
c#
.net
validation
datatable
null
foreach(DataRow row in dataTable.Rows)
{
if(row.IsNull("myColumn"))
throw new Exception("Empty value!")
}
You can null/blank/space Etc value using LinQ Use Following Query
var BlankValueRows = (from dr1 in Dt.AsEnumerable()
where dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
select Columnname);
Here Replace Columnname with table column name and "" your search item in above code we looking null value.
I will do like....
(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))
You can loop throw the rows and columns, checking for nulls, keeping track of whether there's a null with a bool, then check it after looping through the table and handle 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 come out of the foreach loop with a break statement e.g.
//test for null here
if (row[col] == DBNull.Value)
{
tableHasNull = true;
break;
}
To save looping through the rest of the table.
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
Source: Stackoverflow.com