如何处理'源不包含DataRows。 '错误

时间:2015-03-31 10:11:54

标签: asp.net

请找到以下代码。它将通过错误'来源不包含DataRow'如果它是空的..如何处理这个?

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);
                    }

2 个答案:

答案 0 :(得分:1)

像这样使用: -

 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);
                    }

答案 1 :(得分:0)

使用If条件,如下所示。

if(dtTemSec != null)
{
   if(dtTemSec.Rows.Count > 0)
    {
    }
}

编辑:

如果是这种情况,则将条件放在过滤器

之后
if(dtTemSec != null)
    {
       if(dtTemSec.Rows.Count > 0)
        {
           DataTable Temp = new DataTable();
           Temp = dtTemSec.AsEnumerable()
                                        .Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder)
                                        .CopyToDataTable();
           if(Temp != null)
           {
           if(Temp.Rows.Count > 0)
           {
              grdStepDetails.DataSource=Temp;
              grdStepDetails.DataBind();
              ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
           }
           }
        }
    }