Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The source contains no DataRows

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?

like image 830
Mike Avatar asked Feb 04 '15 15:02

Mike


2 Answers

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);
like image 121
J. Steen Avatar answered Nov 19 '22 03:11

J. Steen


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.

like image 9
Steve Avatar answered Nov 19 '22 04:11

Steve