Apollo
Apollo

Reputation: 2070

Gridview Error Data Contains No Rows when Used with Linq

I have this Linq statement that filters transactions. It works fine when it filters but I get an error in dt.AsEnumerable() when there is nothing being returned.

The error is Data contains no row. Anybody know how to handle when there is nothing returned?

      newDataTable = dt.AsEnumerable()
                    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")))
                    .CopyToDataTable();  

      gvMain.DataSource = newDataTable;
      gvMain.DataBind();

Upvotes: 1

Views: 696

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460098

You cannot use CopyToDataTable if the input sequence is empty. So you need to check that first:

var newDataTable = dt.Clone();  // an empty table with the same schema
var ticketRows = dt.AsEnumerable()
    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")));
if(ticketRows.Any())
    newDataTable = ticketRows.CopyToDataTable();

Possible exceptions with CopytoDataTable

  • ArgumentNullException
    The source IEnumerable sequence is null and a new table cannot be created.
  • InvalidOperationException
    • A DataRow in the source sequence has a state of Deleted.
    • The source sequence does not contain any DataRow objects.
    • A DataRow in the source sequence is null.

Upvotes: 3

Cam Bruce
Cam Bruce

Reputation: 5689

Check if your DataTable has any rows before calling AsEnumerable()

    if (dt.Rows.Count > 0)
    {
      newDataTable = dt.AsEnumerable()
                    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")))
                    .CopyToDataTable();  

      gvMain.DataSource = newDataTable;
      gvMain.DataBind();
    }
    else {
    //error
    }

Upvotes: 0

Related Questions