在GridView中找不到基于HiddenField值的ID复选框



我在ASP.NET中有一个GridView,在这个GridView的列中,我有以下控件:

<asp:TemplateField>       
    <ItemTemplate>
        <input id='<%#Eval("po_asn_number") %>' class="css-checkbox" type="checkbox" />                                                       
        <label for='<%#Eval("po_asn_number") %>' name="lbl_1" class="css-label"></label>        
        <asp:HiddenField ID="poid" runat="server" Value='<%#Eval("po_asn_number") %>' />
    </ItemTemplate>                     
</asp:TemplateField>

这是我在Code Behind中的OnClick事件。

protected void create_Click(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in GridView1.Rows)
    {
        HiddenField poid = ((HiddenField)gvr.Cells[0].FindControl("poid"));
        if (((HtmlInputCheckBox)gvr.FindControl(poid.Value)).Checked == true)
        {
            Response.Redirect("ShipmentDetail.aspx?id=" + poid.Value);
        }
        else
        {
            //Do nothing
        }
    }
}

我首先要做的是,查找一个HiddenField,它的值是<input type="checkbox" />的ID。然后我检查checkbox是否已检查。如果是,那就做别的什么也不做。

当点击按钮时,我得到一个错误:

Object reference not set to an instance of an object

Line 48:             if (((HtmlInputCheckBox)gvr.FindControl(checkbox)).Checked == true)
Line 49:             {
Line 50:                 Response.Redirect("ShipmentDetail.aspx?id=" + poid.Value);

如能提供任何帮助,我们将不胜感激。

添加runat属性。

<input id='<%#Eval("po_asn_number") %>' class="css-checkbox" type="checkbox" runat="server"/>

如果没有此属性,就无法在服务器端代码的代码后面找到控件。

还要在获得Hidden field值的地方放置一个断点,以确认您正在获得预期值。

您还需要执行Karl建议的更改以使其发挥作用。

新增:更改此行以为以下行添加单元格[0]:

if (((HtmlInputCheckBox)gvr.Cells[0].FindControl(poid.Value)).Checked == true)

当您在所有网格视图行中循环时,只需要查看数据行,因为当您不只指定数据行时,它会从标题行开始。您将得到异常,因为它无法将FindControl()的结果强制转换为类型。由于标题行中没有具有此名称的控件,FindControl()返回null,并且强制转换失败。

相反:

protected void create_Click(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in GridView1.Rows)
    {
        // Only deal with data rows, not header or footer rows, etc.
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            HiddenField poid = ((HiddenField)gvr.FindControl("poid"));
            // Check if hidden field was found or not
            if(poid != null)
            {
                if (((HtmlInputCheckBox)gvr.FindControl(poid.Value)).Checked)
                {
                    Response.Redirect("ShipmentDetail.aspx?id=" + poid.Value);
                }
                else
                {
                    //Do nothing
                }
            }
        }
    }
}

最新更新