• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5666
  • Last Modified:

LINQ To DataTable, exception if no rows found

Hi Experts,
The below code works find except that if no rows are found, it gives an exception
"Error: Sys.WebForms.PageRequestManagerServerErrorException: The source contains no DataRows."

Any Alternative or Workaround?
Thanks,
Abhinay
DataTable dt = new DataTable();
dt = (DataTable)ViewState["table"];
DataTable newTable = new DataTable();
newTable = dt.AsEnumerable()
            .Where(t => t.Field<string>("EmpID") == txtEmpID.Text.Trim())
            .CopyToDataTable();

GridView1.DataSource=newTable;
GridView1.DataBind();

Open in new window

0
abhinayp86
Asked:
abhinayp86
  • 2
  • 2
1 Solution
 
_Katka_Commented:
Hi, you put a condition there

if (dt.Rows.Count > 0)
{
    newTable = dt.AsEnumerable()
            .Where(t => t.Field<string>("EmpID") == txtEmpID.Text.Trim())
            .CopyToDataTable();
}

regards,
Kate
0
 
abhinayp86Author Commented:
Figured It out...
Thanks
DataTable dt = new DataTable();
        dt = (DataTable)ViewState["table"];
        DataTable newTable = new DataTable();
        newTable = dt.Clone();
        IEnumerable<DataRow> newDataRow = default(IEnumerable<DataRow>);
  newDataRow = dt.AsEnumerable()
                             .Where(t => t.Field<string>("EmpID") == txtEmpID.Text.Trim());
if (newDataRow.Count() > 0)
        {
            newTable = newDataRow.CopyToDataTable();
        }
       
            gvResults.DataSource = newTable;
            gvResults.DataBind();

Open in new window

0
 
abhinayp86Author Commented:
@_Katka_

It isnt when dt has no rows.
The exception occurs when the LINQ query returns no rows(i.e there is no condition satisfying t.Field<string>("EmpID") == txtEmpID.Text.Trim() in dt)

Thanks
0
 
_Katka_Commented:
I'm glad you found it :)

regards,
Kate
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now