dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: .NET, JavaScript
Expertise: Beginner
Feb 23, 2004

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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 given
value
    function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal) {

        re = new RegExp(':' + aspCheckBoxID + '$')  //generated control
name 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
..
<HTML>
    <HEAD>
    ...
        <script language="javascript"
src="/MyWebApp/MyUtils/FormFunctions.js"></script>
    ...
    </HEAD>
..
Finally, add the CheckBox to your DataGrid, including a call to the script in the onclick event:

MyForm.aspx
..
    <Columns>
        <asp:TemplateColumn>
            <HeaderTemplate>
                <input id="chkAllItems" type="checkbox"
onclick="CheckAllDataGridCheckBoxes('chkItemChecked',
document.forms[0].chkAllItems.checked)" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox id="chkItemChecked"
runat="server"></asp:CheckBox>
            </ItemTemplate>
        </asp:TemplateColumn>
..
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.

Greg Dobbs
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date