The code below will throw an error:
The source contains no DataRow
if the row is empty. How can I handle this error in code so it does not throw an exception?
if (dtTemSec.Rows.Count > 0)
{
grdStepDetails.DataSource = dtTemSec.AsEnumerable()
.Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder)
.CopyToDataTable();
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
else
{
grdStepDetails.DataSource = null;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
Use like this:
if (dtTemSec.Rows.Count > 0)
{
var table = dtTemSec;
var rows = table.AsEnumerable().Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder);
var dt = rows.Any() ? rows.CopyToDataTable() : table.Clone();
grdStepDetails.DataSource = dt;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
else
{
grdStepDetails.DataSource = null;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}