I am getting an error "The source contains no Datarows"

Hi,

I am filtering records using linq based on the column PROD_DATE, when the records are found there is no issue, however when there are no matching PROD_DATE it throws me an error. “The source contains no DataRows”.

Source Data

MATERIAL_DOCUMENT PROD_DATE PLANT_CODE MATERIAL PROD_QTY
4910113193 3/17/2022 00:00:00 BLR AAA1 43
4910113188 3/17/2022 00:00:00 BLR MJK1 17
4910113194 3/24/2022 00:00:00 BLR LKIM 10
4910113189 3/24/2022 00:00:00 BLR MMRT 21

dt_Test.AsEnumerable.Where(function (newrow) datetime.ParseExact(newrow(“PROD_DATE”).tostring,“MM/dd/yyyy hh:mm:ss”,system.Globalization.CultureInfo.InvariantCulture).ToString(“MM/dd/yyyy”) = datetime.Now.ToString(“MM/dd/yyyy”)).copytodatatable

Regards,
Manjesh

Hi @manjesh_kumar ,

That is the expected outcome, since the filtering produces zero results.
None of the entries match with today’s date (03/25/2022).

If you are wondering why you are recieveing this error, that is because a DataTable will not accept empty rows i.e., it has to contain at least one row.

To handle this, output it to a List of DataRows first, then check if the Count is greater than zero, and only then copy it to a datatable.

dt_Test.AsEnumerable.Where(function (newrow) datetime.ParseExact(newrow(“PROD_DATE”).tostring,“MM/dd/yyyy hh:mm:ss”,system.Globalization.CultureInfo.InvariantCulture).ToString(“MM/dd/yyyy”) = datetime.Now.ToString(“MM/dd/yyyy”)).ToList()
lst_variable.Count()>0

Then->

dt_Test.AsEnumerable.Where(function (newrow) datetime.ParseExact(newrow(“PROD_DATE”).tostring,“MM/dd/yyyy hh:mm:ss”,system.Globalization.CultureInfo.InvariantCulture).ToString(“MM/dd/yyyy”) = datetime.Now.ToString(“MM/dd/yyyy”)).copytodatatable

Kind Regards,
Ashwin A.K

1 Like

Hello @ashwin.ashok

Thank you for that quick response and works as expected.
I did this through the conventional method, could this be achieved through same linq statement which was posted earlier.

Regards,
Manjesh

Hi @manjesh_kumar ,

You have handled it correctly now!
And no, the earlier LINQ statement cannot handle null exceptions which is why we have to add it to a list to validate the results before pushing it to a Datatable.

Kind Regards,
Ashwin A.K

Hello @ashwin.ashok ,

My question was is there a possibility to extend that LINQ after some modification.

Regards,
Manjesh

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.