从数据网格中捕获已检查的值

时间:2016-02-06 02:32:37

标签: c# asp.net checkbox

我继续收到错误

  

对象未设置为对象的实例

我需要更改哪些内容才能成功执行此代码?

HTML

<td valign="top" style="text-align: left; width: 200px;">
<asp:GridView runat="server" ID="datagridTest" AutoGenerateColumns="false" GridLines="Both" ShowFooter="true" >
<Columns>
<asp:BoundField DataField="field1" HeaderText="1st Set" />
<asp:BoundField DataField="field2" HeaderText="2nd Set" />
<asp:TemplateField>
    <ItemTemplate>
        <asp:Label runat="server" Text='<%#Eval("categoryID") %>' ID="managerID" Visible="false"></asp:Label>
     </ItemTemplate>
    <ItemTemplate>
        <asp:CheckBox ID="Checked" runat="server" AutoPostBack="false" Checked='<%# Convert.ToBoolean(Eval("Checked")) %>' />
    </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>                                
<asp:Button runat="server" ID="btnChecked" CssClass="Buttons" Text="Add" OnClick="btnC_Click" />
</td>

C#

protected void btnC_Click(object sender, EventArgs e)
{
try
{
    foreach (GridViewRow row in datagridTest.Rows)
    {
        string ID = ((Label)row.FindControl("managerID")).Text;
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chk = (CheckBox)row.FindControl("Checked");
            if (chk.Checked) {}
            else {}
        }
    }
}
catch (Exception exception) { throw exception; }
}

1 个答案:

答案 0 :(得分:0)

在您的html中,您将gridviews id设置为

  

ID =&#34; datagridTest&#34;

但在你背后的代码中使用&#34; dgRD&#34;。这可能是你的问题根源。