Faraz Shah Khan

MCP, MCAD.Net, MCSD.Net, MCTS-Win, MCTS-Web, MCPD-Web

Check/Uncheck checkboxes in GridView using javascript

Seen a lot of questions regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript. So I thought to put it on my blog for quick reference for others and for myself. Following is the code:
------------------------------------------- .aspx code ---------------------------------------------
<script type="text/javascript">
function SelectAll(id)
      {
       var frm = document.forms[0];
           
            for (i=0;i<frm.elements.length;i++)
            {
                if (frm.elements[i].type == "checkbox")
                {
           frm.elements[i].checked = document.getElementById(id).checked;
                }
            }
        }
               
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
        <Columns>
            <asp:TemplateField>
                <AlternatingItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </AlternatingItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
                <HeaderTemplate>
                    <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
                </HeaderTemplate>
                <HeaderStyle HorizontalAlign="Left" />
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

----------------------------------------- .vb file if VB.Net is the language ------------------------------------------
VB.Net Code

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.Header) Then
            'adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
            DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
        End If
    End Sub


----------------------------------------- .cs file if C#.Net is the language ------------------------------------------
C#.Net Code


protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.Header))
        {
            //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
            ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
        }
    }

Comments

AndrewSeven said:

What about other forms and unrelated checkboxes in the same page?

# February 13, 2008 9:22 AM

Justin said:

Couldn't you put a name attribute on the checkboxes and then call document.getElementsByName to get a reference to the controls versus looping through all of the controls in the gridview.

# February 13, 2008 10:46 AM

pandu said:

very precise and neat example/code. Straight to the point with min code.

works good.

# February 13, 2008 5:49 PM

farazsk11 said:

Hi Andrew,

In this case which honestly speaking I rearely found you can make this addition to your javascript if statement

if (frm.elements[i].type == "checkbox" && frm.elements[i].id.indexOf("<%= GridView1.ClientID %>") == 0)

               {

                   frm.elements[i].checked = document.getElementById(id).checked;

               }

As all the controls within GridView control will have a ClientID of GridView as the prefix. Now place as many check boxes as you want out side the grid view only the one inside it will be affected.

# February 14, 2008 8:36 PM

farazsk11 said:

Hi Justin,

According to my understanding I don't think it would be effective because you never know how many checkboxes will be created at runtime. As far as their ids are concerned it will be somthing like this

GridView1_ctl01_CheckBox1

here GridView1 is the client id for the GridView

CheckBox1 is the id for the checkbox

and GridView1_ctl01_CheckBox1 is the clientID for that particular check box. ctl01 will not remain same it will be ctl02, ctl03 for the next checkbox in the row.

So if there are 50 rows you have to write 50 document.getElementById's assuming that you have fixed 50 rows and not more. I believe looping so far seems to be the more straight forward and easy approach.

# February 14, 2008 8:50 PM

Trung said:

Great Job, Thanks

# February 20, 2008 4:53 AM

chris fox said:

Your gridview needs to callout the event OnRowDataBound="GridView1_RowDataBound"

# April 1, 2008 3:01 PM

meera said:

I have a requirement here..........

automatically check gridview's header checkbox when all of the row checkboxes a re checked and when atleast one row checkbox is unchecked,header checkbox should be unchecked.How to get the client id of the header checkbox when a row checkbox is clicked??????

Pls help

# May 9, 2008 5:42 AM

vinay said:

its very urgent

# July 4, 2008 1:05 AM

nisarkhan said:

next time let the credit goes where it belongs to

here is the orginal link where he copied from:

wiki.asp.net/.../check-uncheck-checkboxes-in-gridview-using-javascript

# July 8, 2008 3:40 PM

vinesh said:

The code is perfect.

Thanks for posting this.

# July 16, 2008 3:35 AM

farazsk11 said:

#nisarkhan probably what you see on wiki was also posted by me if i m not mistaken, and there are people who can make modifications in what you have posted by the way even on wiki i have not posted it i can say it was copied from here :).

NOTE:

for all the readers of the post I wrote a better way on check/unchecking checkboxes in gridview in this article www.codeproject.com/.../GridCheckBox.aspx

# July 23, 2008 9:34 AM

Mohammed Imran said:

Hi Faraz,

I would like to know how we can validate checkboxes in same row?

Suppose i have two checkboxes in one row, one for 'Approve' and the other for 'Reject'.

If either one is checked then the other one should be unchecked in the same row.

How do we achieve this?

Your help in this regard will be appreciated.

Kindly send mail at imran.gummi@almarai.com

Thanks and Regards,

Mohammed Imran

# August 2, 2008 6:10 AM

NetMasterr said:

Your Function is working fine but keep in mind that it will select all the checkbox on the form. To avoid this problem use the following snippet.

function SelectAll(id)

     {

      var frm = document.forms[0];

           for (i=0;i<frm.elements.length;i++)

           {

               if (frm.elements[i].type == "checkbox" && frm.name.indexOf('chk')>0)//'chk' is the name of the control in the gridview whose name can be different.

               {

          frm.elements[i].checked = document.getElementById(id).checked;

               }

           }

       }

# August 29, 2008 4:43 AM

farazsk11 said:

I wrote a better version for the same task here www.codeproject.com/.../GridCheckBox.aspx

# August 30, 2008 1:35 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)