将复选框添加到ASP.NET网格视图
我试图在我的网络应用中启用批量删除功能。我显示的数据位于 GridView
中,并且我想添加一列,其中包含每行的一个复选框(或任何其他选项)。用户可以标记行删除,然后一次删除所有行。
I am trying to enable bulk deleting in my web app. The data I am displaying is in a GridView
and I want to add a column which would contain one checkbox (or any alternative) for every row. The user could mark rows to delete and then delete all of them at once.
当我添加 CheckBoxField
时,它必须绑定到我自然没有的DataTable中的列。我尝试以编程方式向DataTable添加新列,但无论我做什么,它都呈现为只读。
When I add a CheckBoxField
, it must be bound to a column which I, naturally, don't have in the DataTable. I tried adding a new column to the DataTable programatically, but it is rendered as read-only whatever I do.
数据从数据库检索到一个DataTable,我添加到一个DataSet并绑定到GridView作为它的数据源。
The data is retrieved from the DB into a DataTable, which I add to a DataSet and bind to the GridView as its data source.
有没有一种方法可以实现这一点?
Is there a way I could achieve this?
您可以使用CheckBox为您的GridView添加 TemplateField
。您甚至可以在标题中添加一个全选复选框。您仍然需要单独的删除按钮
You can add a TemplateField
to your GridView with the CheckBox. You can even add one in the header for a "select all" checkbox. You will still need a separate delete button
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" CssClass="headerCheckBox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" CssClass="rowCheckBox" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script type="text/javascript">
$(document).ready(function () {
$("#<%= GridView1.ClientID %> .headerCheckBox").change(function (e) {
$("#<%= GridView1.ClientID %> .rowCheckBox input").each(function () {
$(this).prop("checked", $(e.target).prop("checked"));
});
});
});
</script>