Add checkbox to ASP.NET grid view

asp.net, c#, datatable, gridview

Solution

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>

Problem

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. 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. 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?

Original source