如何在 Gridview 中获取一列复选框?

How to get a column of checkboxes in Gridview?

需要注意的是,我在 Visual Studio 2013 Express for Web 中完成了所有这些工作。

我有一个 GridView,它的数据是由 SqlDataSource 生成的。目前,当我测试页面时。生成如下所示的 table:

CustomerID    CustomerName    CustomerAddress
-----------   ------------    ----------------
1             Bob             Address
2             John            Address
3             Smith           Address

不过,我真的很想要这个:

CustomerID    CustomerName    CustomerAddress
-----------   ------------    ----------------
[]             Bob             Address
[]             John            Address
[]             Smith           Address

我希望 CustomerID 字段为 "hidden field" 并在其位置有一个复选框。然后,我希望复选框的值是该行的 CustomerID。但是,我终生无法将复选框放在那里,它仍然只是显示 CustomerID 本身。最后,我想创建一个按钮来删除选中的行,并通过 DELETE FROM TABLE 将其反映在数据库中。这就是为什么我希望复选框也 "have" 该特定行的 CustomerID 的值。

代码如下:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="RowsInGroup" >
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
                <asp:BoundField DataField="CustomerAddress" HeaderText="CustomerAddress" SortExpression="CustomerAddress" />
                <asp:TemplateField></asp:TemplateField>
            </Columns>
</asp:GridView>

如果工具箱中有更好的数据对象可供使用,我会洗耳恭听。

感谢您提供的任何建议!

你的问题已经解决了一半。通过使用 DataKeyNames="CustomerID",您不需要隐藏字段来保存此值。

首先,创建您的复选框列。有多种方法可以实现这一点。这是一个:

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="chkDelete" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

然后在任何处理删除的事件中,只需遍历 GridView 中的每一行并在每一行中找到复选框。如果选中,则对该行使用 DataKey 以获取 CustomerID.

protected void btnDelete_Click(object sender, EventArgs e)
{
    List<string> customersToDelete = new List<string>();
    foreach(GridViewRow row in GridView1.Rows)
    {
        CheckBox chkDelete = (CheckBox)row.FindControl("chkDelete");
        if(chkDelete.Checked)
        {
            DataKey key = GridView1.DataKeys[row.DataItemIndex];
            customersToDelete.Add(key.Value.ToString());
        }
    }
}