Hi everybody,
I need to do a test in a DataView to check if at least one row contains one cell with a null value. What is the best way to do it in your opinion ?
Thanks in advance.
Hi everybody,
I need to do a test in a DataView to check if at least one row contains one cell with a null value. What is the best way to do it in your opinion ?
Thanks in advance.
As SLaks mentioned, you're going to need to loop over the rows and the items in each row. You can do this with LINQ like this:
bool hasNull = view.Table.Rows.OfType<DataRow>()
.Any(r => r.ItemArray.Any(o => o == DBNull.Value));
Or you can write the loop yourself, something like:
private bool HasEmptyItem(DataView view)
{
foreach (DataRow row in view.Table.Rows)
{
foreach (DataColumn col in view.Table.Columns)
{
if (row[col] == DBNull.Value)
return true;
}
}
return false;
}
While the LINQ version is a lot more compact, it's still going to loop over the rows and columns, so take your pick.
Update:
Based on comments, here's a better sample based on what you're trying to do. This simply loops over the rows, and checks if a give column is null (make sure to use DBNull.Value
with a DataTable
), and if so, just sets it to false to prevent problems in your case. Just change IS_DEFAULT_COL
to be the correct index.
const int IS_DEFAULT_COL = 1;
foreach (DataRow row in view.Table.Rows)
{
if (row[IS_DEFAULT_COL] == DBNull.Value)
row[IS_DEFAULT_COL] = false;
}