[Solved] Remove empty rows "System.InvalidOperationException: 'Thesource contains no DataRows.'" in .CopyToDataTable();

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.

System.InvalidOperationException: ‘The source contains no DataRows.’

For me, the code below is what triggered the System.InvalidOperationException: ‘The source contains no DataRows.’ exception

GetCustomerDetails() method


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.

Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am currently focused on continuous improvement and agile project management.

Post a Comment

Previous Post Next Post