39
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?

3
  • Just to make sure, you do want only entries that are for today or some day in the future?
    – ryanyuyu
    Commented Feb 4, 2015 at 15:15
  • its is occuring because no records matches or full fill the query condition and result is null so here im trying to copy null to datatable ...
    – Mike
    Commented Feb 4, 2015 at 15:15
  • when you are populating the DataTable could you not change the query in regards to the sql used to populate the initial DataTable..? also what if you were to change the labda expression to a Linq query.. have you thought about that as well msdn.microsoft.com/en-us/library/… || msdn.microsoft.com/en-us/library/bb386921%28v=vs.110%29.aspx || forums.asp.net/t/…
    – MethodMan
    Commented Feb 4, 2015 at 15:17

2 Answers 2

57

ds.Tables[4] might have rows, 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 using .Any() 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);
3
  • its is occuring because no records matches or full fill the query condition and result is null so here im trying to copy null to datatable .
    – Mike
    Commented Feb 4, 2015 at 15:17
  • @Mike Like I said - splitting your method chain and checking your interim results is one way to go. The comments on your question have suggested another.
    – J. Steen
    Commented Feb 4, 2015 at 15:22
  • @Mike I just verified both solutions, and both work with a rather simplified datamodel. There must be something else going on.
    – J. Steen
    Commented Feb 4, 2015 at 15:37
9

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.