Learning While Aging

[JavaScript] CheckAll/CheckNone CheckBox in GridView

GridView or DataGrid only allows you to delete one row each time and it becomes inefficient and tedious if there are multiple rows need to be deleted. In this post, I will demo how to add a check box in front of each row and also a check box in the header of the grid to check/uncheck all check boxes, then with a delete button to delete those checked rows in a batch mode.

I will use the Employees table in the Northwind database of SQL Server 2000 and also use SqlDataSource object to process data. Here is the screen shot of the final grid view.

GridView with check all/check none check box

In this tutorial, I will demo how to implement this “check all”/”check none” feature with JavaScript to avoid any post-backs, just like any email client does.

1. Let’s add a CheckBox control in fron of each row of the GridView. It can be done by adding a TemplateField in the GridView. The quickest way to do it is through the Edit Column interface of the GridView in Visual Studio 205. Just add a CheckBoxField to the columns, then click “Convert this field into a TemplateField” link to convert it into a TemplateField. Then go to Edit Template interface, in the HeaderTemplate field name the CheckBox control “cbHeaderSelect”, and in the ItemTemplate field name the CheckBox control “cbRowSelect”.

2. Add JavaScript functions to check/uncheck all checkboxes.

<script language="javascript" type="text/javascript">
    function changeCheckBoxesState(checkBoxIDs)
    {
        var hd = document.getElementById(checkBoxIDs);
        var IDs = hd.value.substring(0, hd.value.length - 1);
        var arrCheckBoxIDs = IDs.split("|");

        var cbHeader = document.getElementById(arrCheckBoxIDs[0]);
        if (cbHeader.checked)
        {
            for (i=1; i<arrCheckBoxIDs.length; i++)
            {
                var cb = document.getElementById(arrCheckBoxIDs[i]);
                cb.checked = true;
            }
        }
        else
        {
            for (i=1; i<arrCheckBoxIDs.length; i++)
            {
                var cb = document.getElementById(arrCheckBoxIDs[i]);
                cb.checked = false;
            }
        }
    }

    function changeHeaderCheckBoxState(checkBoxIDs)
    {
        var hd = document.getElementById(checkBoxIDs);
        var IDs = hd.value.substring(0, hd.value.length - 1);
        var arrCheckBoxIDs = IDs.split("|");
        for (i=1; i<arrCheckBoxIDs.length; i++)
        {
            var cb = document.getElementById(arrCheckBoxIDs[i]);
            if (!cb.checked)
            {
              var cbHeader = document.getElementById(arrCheckBoxIDs[0]);
              cbHeader.checked = false;
              return;
            }
            var cbHeader = document.getElementById(arrCheckBoxIDs[0]);
            cbHeader.checked = true;

        }
    }
</script>

The first function takes a parameter that stores the ID’s of all check boxes. Those ID’s are stored in a HiddenField server control as a pipe-delimitered string, and the JavaScript code will parse the string to get the check box ID’s and loop through them to check/uncheck those boxes.

The second function is used to change the state of the CheckAll/CheckNone hearder check box. For example, if all check boxes in the grid view are manually checked, then the header check box should be checked automatically. On the other hand, if any check box in the grid view is unchecked, then the hearder check box should becomae uncheck automatically as well.

3. Store the ID’s of the check boxes in the code-behind and pass them to the JavaScript functions. This is implemented in GridView’s RowDataBound event handler as follows:

Private Sub gvEmployee_RowDataBound(ByVal sender As Object, ByVal e As _
                  System.Web.UI.WebControls.GridViewRowEventArgs) _
                  Handles gvEmployee.RowDataBound
    If (e.Row.RowType = DataControlRowType.Header) Then
        Dim cbHeader As CheckBox = CType(e.Row.FindControl("cbHeaderSelect"), CheckBox)
        cbHeader.Attributes.Add("onclick", "changeCheckBoxesState('" & _
                    Me.hdCheckBoxIDs.ClientID.ToString() & "')")
        Me.hdCheckBoxIDs.Value = cbHeader.ClientID.ToString() & "|"
    End If
    If (e.Row.RowType = DataControlRowType.DataRow) Then
        Dim cbRow As CheckBox = CType(e.Row.FindControl("cbRowSelect"), CheckBox)
        Me.hdCheckBoxIDs.Value += cbRow.ClientID.ToString() & "|"
        cbRow.Attributes.Add("onclick", "changeHeaderCheckBoxState('" & _
                    Me.hdCheckBoxIDs.ClientID.ToString() & "')")
    End If
End Sub

4. Finally, add the code to process the batch deletion:

Protected Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                        Handles btnDelete.Click
    For Each gvr As GridViewRow In Me.gvEmployee.Rows
        Dim cb As CheckBox = CType(gvr.FindControl("cbRowSelect"), CheckBox)
        If (cb.Checked) Then
            Dim ID As Integer = Me.gvEmployee.DataKeys(gvr.RowIndex).Value
            Me.SqlDataSource1.DeleteParameters("employeeID").DefaultValue = ID
            Me.SqlDataSource1.Delete()
        End If
    Next
    Me.gvEmployee.DataSourceID = "SqlDataSource1"
    Me.gvEmployee.DataBind()
End Sub

Notes: to simplify the tutorial, I didn’t add confirmation for deleting the rows. In practice, any action that causes deleting records should have a confirmation before the actual deletion takes place.

More screen shots:

Check all check boxes

Check rows to delete

Multiple rows deleted

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x