The exception System.InvalidOperationException: ‘The source contains no DataRows.’ occurs when we are working with DataTable objects. Let us try to analyze the issue and also obtain what is the solution.
For me, the code below is what triggered the System.InvalidOperationException: ‘The source contains no DataRows.’ exception
GetCustomerDetails() method
Solution
To solve the above error, It’s just a matter of check/test i.e either table contains any rows or the input sequence as the type of DataRow objects. In the code example, once we remove the empty rows from DataRowCollection, it’s empty. Here you are trying to copy empty DataRow objects to the table using DataTableExtensions.CopyToDataTable()
method, hence copyToDataTable throws an error “The source contains no DataRows.”, Even though the table has no DataRow objects after filtered. an easier way to solve the above issue using the Linq extension method Any()
.
rows.Any() ? rows.CopyToDataTable() : table.Clone();
In code example it could be :
Tip: How to use DataTableExtensions.CopyToDataTable Method ?
The CopyToDataTable method takes the results of a query and copies the data into a DataTable, CopyToDataTable<T>
extension methods that accept a generic parameter of a type other than DataRow. It’s useful when you want to return a DataTable
type when you performed some operations like filter, select, or any in-memory with LINQ extension methods.