Check All CheckBoxes in an ASP.NET DataGrid Using a Single CheckBox

Do you have any DataGrids in your ASP.NET application with a CheckBox for each row? If so, you may have wanted a faster way to check or uncheck all items. One way uses a single CheckBox in the header or footer of that DataGrid. This tip shows you how.

First, create a JavaScript file for your application, which includes the following function:

FormFunctions.js..    //checks all DataGrid CheckBoxes with the given name with the givenvalue    function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal) {        re = new RegExp(':' + aspCheckBoxID + '$')  //generated controlname starts with a colon        for(i = 0; i < document.forms[0].elements.length; i++) {            elm = document.forms[0].elements[i]            if (elm.type == 'checkbox') {                if (re.test(elm.name)) {                    elm.checked = checkVal                }            }        }    }..

The script takes the name of the DataGrid CheckBox to be checked and the value to apply (checked or unchecked).

In your .aspx file, you need to include the JavaScript file as follows:

MyForm.aspx..        ...            ...    ..

Finally, add the CheckBox to your DataGrid, including a call to the script in the onclick event:

MyForm.aspx..                                                                                                    ..

Notice that the call to the JavaScript function passes in the name of the CheckBox appearing on each row and the value of the check all CheckBox.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: