The source contains no DataRows

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?

 

回答

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);

 

posted @ 2021-09-24 10:44  ChuckLu  阅读(659)  评论(0编辑  收藏  举报