'DataTable RowFilter avoid Source contains no data rows Exception
im using following code to get a filtered DataTable
DT = NewMobileFa.GetNewMobile().AsEnumerable().Where(r => arrList.Contains(r.Field<int>("NewMobileID")) && r.Field<string>("Status") == "OF").CopyToDataTable();
this code gives me the error
Source contains no data rows
which is correct and actually there is no data
what i need is,i need to avoid the exception if there are no data rows and just to return the empty DataSource.
can i achieve this?
Solution 1:[1]
you can do like this. first you need to get all the rows. then check for count of the retrived rows. you can check MSDN DataTable.CopyToDataTable, it has nice explanation
var Rows = NewMobileFa.GetNewMobile().AsEnumerable().Where(r => arrList.Contains(r.Field<int>("NewMobileID")) && r.Field<string>("Status") == "OF");
Now use the rows to check whether data is there or not
if(Rows.Count()>0)
{
DataTable dt = Rows.CopyToDataTable();
}
Solution 2:[2]
This issue seems to be fixed in 4.0 although it's not marked so.
A quick test on 4.0 works as expected:
tbl.AsEnumerable().Where(r=>1==2).CopyToDataTable();
It will successfully create a DataTable with 0 rows whether or not source DataTable is empty.
If you are using an older version of the .NET framework, use one of its overloads like CopyToDataTable(IEnumerable, DataTable, LoadOption) which don't throw an exception if there are no rows in the source DataTable.
Or use one of the suggested approaches here:
How to deal with a flaw in System.Data.DataTableExtensions.CopyToDataTable()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ravi Gadag |
| Solution 2 | Community |
