【问题标题】:Find Control returns Null Exception查找控件返回空异常
【发布时间】:2016-06-16 05:24:49
【问题描述】:

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

      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。我什至没有动态添加任何控件。可能是什么原因?

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    GridView 不仅有 DataRows,还有其他的行类型,如页眉、页脚。您的控件是 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);
    
            }
        }
    }
    

    【讨论】:

    • 我已经做到了。原来它确实是一个数据行
    • 是否从 FindControl 中获取了 rowId 的 null,如何查找其他控件?
    • 我无法从 gvrow 获得任何控制
    • 你是否使用了条件 if(gvrow.RowType == DataControlRowType.DataRow) 的代码?
    • 添加有问题的 GridView HTML 并显示将数据绑定到 GridView 的方式和位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2023-03-31
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多