Gridview Check/Uncheck all records using JavaScript

Hi Guys,

While working with GridView , couple of times you may have to face a situation where you might have to check/uncheck all records of gridview basically to write your changes back to database. Following the the java script function you can use for this purpose. Wither you can use this methods in same page or put it into a separate .js file and pass a reference of that .js file into current page where ever you want to use the same.

Function:

<script type="text/jscript" language="javascript">
    function SelectAllCheckboxes(chkAll, chkCtrlId) {
        checked = chkAll.checked;
        elm = chkAll.form.elements;
        for (i = 0; i < elm.length; i++)
            if (elm[i].type == "checkbox" && elm[i].id.indexOf(chkCtrlId) != -1) {
                if (elm[i].checked != checked)
                    elm[i].click();
            }
    }
</script>

Add this TemplateField to the Gridview that creates checkboxes in HeaderRow and DataRows and also call the above javascript function on the click of checkbox of the Gridview HeaderRow  sp:TemplateField HeaderText="Select">
<asp:TemplateField HeaderText="Select">
    <ItemTemplate>
        <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    <HeaderTemplate>
        <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this, 'chkSelect');" runat="server"
            type="checkbox" />
    </HeaderTemplate>
</asp:TemplateField>



Advertisements

One thought on “Gridview Check/Uncheck all records using JavaScript

  1. I’ve got to throw a HUGE thank you your way mate! I’ve been trying to work this out for days and I just couldn’t get the code quite right, now it works perfectly!

    nice one!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s