tags:

views:

54

answers:

2

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.

+1  A: 

Without measuring, I would guess that the answer is a nested loop.

SLaks
something like :foreach (DataRow dr in TheDataView){ if dr["Column"] == Null ... } ?
benj007
And then loop through each column.
SLaks
+2  A: 

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;
}
wsanville
Thanks a lot wsanville !I was thinking of this regular loop but your LinQ solution seems to be a lot more interesting and compact :)Could you tell me your opinion about the inital problem I have and I have explained in my last comment above please ? because maybe I could solve that directly in the binding process instead of trying to test the dataview.
benj007
thanks,I remember I tried something in my binding stuff to say "if it's null then bind with false", there is an option for that when you do checkbox.databindings.add(........) I think, but that didn't seem to work, I still got an error.
benj007
Don't call `ItemArray`; it needlessly allocates an array.
SLaks
hello,I have a problem with the linq version because I have a filter on my dataview and I only want to loop through the filtered rows, so I know how to change the regular code to do that, like this :foreach (DataRowView drv in View)... instead of (DataRow row in view.Table.Rows)But I don't find how to change the linq version to loop only through the filtered rows.Thanks a lot !
benj007