0

我在 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>

这是我在后面的代码中的 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" />. 然后我正在检查是否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);

您可以提供的任何帮助将不胜感激。

4

2 回答 2

1

添加runat属性。

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

没有这个属性,就无法在服务器端代码后面的代码中找到控件。

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

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

新增: 更改此行以添加 Cells[0] 为下面的行:

if (((HtmlInputCheckBox)gvr.Cells[0].FindControl(poid.Value)).Checked == true)
于 2013-08-28T18:54:52.437 回答
0

当您循环浏览所有网格视图行时,您只需要查看数据行,因为当您不只指定数据行时,它会从标题行开始。您收到异常,因为它无法将结果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
                }
            }
        }
    }
}
于 2013-08-28T18:48:32.697 回答