Find Control返回Null Exception

时间:2016-06-16 05:24:49

标签: c# asp.net gridview

我有一个asp .Net页面,其中有一个名为rowId的labe

      protected void testResultsGridView_onRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string str = string.Empty;
        GridViewRow row = testResultsGridView.Rows[e.RowIndex];
        Int32 id = Int32.Parse(((Label)row.FindControl("rowId")).Text);
        String Cause = ((DropDownList)row.FindControl("Cause")).SelectedValue;
        String comment = ((TextBox)row.FindControl("comment")).Text;
        String check = ((TextBox)row.FindControl("check")).Text;
        String reRunStatus = ((DropDownList)row.FindControl("Status")).SelectedValue;
        String subCategory = ((DropDownList)row.FindControl("Category")).SelectedValue;


        foreach (GridViewRow gvrow in testResultsGridView.Rows)
        {
            CheckBox chk = (CheckBox)gvrow.FindControl("cbSelect");
            if (chk != null && chk.Checked)
            {
                 id = Int32.Parse(((Label)gvrow.FindControl("rowId")).Text); ;

                UpdateTestCase(id, rootCause, subCategory, comment, RTC, reRunStatus);

            }
        }
        testResultsGridView.EditIndex = -1;
        BindData();
    }

在这种情况下,首先找到对rowId返回值的控制,然后在所选scheckbox中找到第二个返回null。我甚至没有动态添加任何控件。可能是什么原因?

1 个答案:

答案 0 :(得分:2)

GridView不仅有DataRows,还有其他行类型,如header,foooter。您的控件是DataRow类型。您需要检查您尝试查找rowId的行是否为DataRow,因为还有其他行类型无法与id rowId进行控制您可以找到有关RowType here的更多信息。您必须找到RowTypeDataRow的控件。

if(gvrow.RowType == DataControlRowType.DataRow)

为何第一次有效

它首次运行,因为事件onRowUpdating是在具有DataRow类型的行上触发的。

为什么第二次不起作用

第二次迭代GridView的行也有其他行类型。如果您调试代码,当RowType不是DataRow时,您将看到它将为空。

您的代码将是

foreach (GridViewRow gvrow in testResultsGridView.Rows)
{
   if(gvrow.RowType == DataControlRowType.DataRow)
   {
        CheckBox chk = (CheckBox)gvrow.FindControl("cbSelect");
        if (chk != null && chk.Checked)
        {
             id = Int32.Parse(((Label)gvrow.FindControl("rowId")).Text); ;

            UpdateTestCase(id, rootCause, subCategory, comment, RTC, reRunStatus);

        }
    }
}
相关问题