Reputation: 141
I need to remove the row from datatable even if any column in the datatable has empty values.
For Example :
My datatable has two columns
Value Input
Dep Phase 1
Sec
Div Phase 2
Result
Value Input
Dep Phase 1
Div Phase 2
I want to remove the second row as Input column has empty values. I'm stuck with the below code.
dtTable = dtTable.Rows.Cast<DataRow>()
.Where(row => !row.ItemArray.All(field => field is DBNull || string.IsNullOrWhiteSpace(field as string))).
.CopyToDataTable();
Can anyone suggest me how this can be achieved ?
Upvotes: 2
Views: 3977
Reputation: 1
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (dt.Rows[i][1] == DBNull.Value)
{
dt.Rows[i].Delete();
}
}
dt.AcceptChanges();
it remove empty rows in th data table
Upvotes: 0
Reputation: 27
Try this:
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (dt.Rows[i]["Column2"].ToString() == "")
{
dt.Rows[i].Delete();
dt.AcceptChanges();
}
}
Upvotes: 0
Reputation: 107
If for loop can be used. We can check each row and column for nulls
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (dt.Rows[i]["col1"] == DBNull.Value || dt.Rows[i]["col2"] == DBNull.Value)
{
dt.Rows[i].Delete();
}
}
Upvotes: 1
Reputation: 62498
According to the requirements you are mentioning you would need to use Any
which will check that if at least column has null
value or empty string it would filter out that row. So, do like:
row => !row.ItemArray.Any(field => field is DBNull ||
string.IsNullOrWhiteSpace(field as string))
If your all columns are of type string
then the above code would work fine, otherwise you will need to convert it to string explicitly by calling ToString()
:
row => !row.ItemArray.Any(field => field is DBNull ||
string.IsNullOrWhiteSpace(field.ToString()))
This will now only return those rows for which every column has value in it.
Upvotes: 1