DataTable dt = ds.Tables[4].AsEnumerable()
.Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date)
.CopyToDataTable();
ds.Tables[4]
has rows but it throws the exception
"The source contains no DataRows."
Any idea how to handle or get rid of this exception?
ds.Tables[4]
might, but the result of your linq-query might not, which is likely where the exception is being thrown. Split your method chaining to use interim parameters so you can be dead certain where the error is occurring. It'll also help you check for existing rows before you call CopyToDataTable()
and avoid said exception.
Something like
DataTable dt = null;
var rows = ds.Tables[4].AsEnumerable()
.Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
if (rows.Any())
dt = rows.CopyToDataTable();
Another option is to use the ImportRow
function on a DataTable
DataTable dt = ds.Tables[4].Clone();
var rows = ds.Tables[4].AsEnumerable()
.Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
foreach (var row in rows)
dt.ImportRow(row);
Simply splitting in two lines
var rowSources = ds.Tables[4].AsEnumerable()
.Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
if(rowSources.Any())
{
DataTable dt = rowSources.CopyToDataTable();
... code that deals with the datatable object
}
else
{
... error message ?
}
This allows to check if the result contains any DataRow, if yes then you could call the CopyToDataTable method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With