Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to select/deselect checkboxes in gridview Or check/uncheck all the checkboxes in gridview using header checkbox or select header checkbox if all checkboxes selected in gridview using JavaScript.

Mar 1, 2011
Introduction:
In this article I will explain how to select/deselect all the checkboxes in gridview using JavaScript.
Description:

I have a one gridview with checkboxes here my requirement is if I select header checkbox of gridview I need to select all the child checkboxes in gridview and if I deselect header checkbox I need to deselect all the child checkboxes in gridview and if I select all the child checkbox I need to select the header checkbox and if any child checkbox deselected I need to deselect header checkbox for this I have written JavaScript function to achieve this functionality.

Design your aspx page like this



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Check/Uncheck all the Checkboxes in Gridview</title>
<script type="text/javascript">
// Select/Deselect checkboxes based on header checkbox
function SelectheaderCheckboxes(headerchk) {
debugger
var gvcheck = document.getElementById('gvdetails');
var i;
//Condition to check header checkbox selected or not if that is true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
//function to check header checkbox based on child checkboxes condition
function Selectchildcheckboxes(header) {
var ck = header;
var count = 0;
var gvcheck = document.getElementById('gvdetails');
var headerchk = document.getElementById(header);
var rowcount = gvcheck.rows.length;
//By using this for loop we will count how many checkboxes has checked
for (i = 1; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
if (inputs[0].checked) {
count++;
}
}
//Condition to check all the checkboxes selected or not
if (count == rowcount-1) {
headerchk.checked = true;
}
else {
headerchk.checked = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvdetails" runat="server" DataSourceID="dsdetails" onrowdatabound="gvdetails_RowDataBound" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectheaderCheckboxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsdetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInfo" >
</asp:SqlDataSource>
</div>
</form>
</body>
</html>  
After completion of aspx page design write the following code in codebehind


protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox headerchk = (CheckBox)gvdetails.HeaderRow.FindControl("chkheader");
CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");
childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");
}
}
After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >


Demo

This will work perfectly for gridview if you didn’t apply any paging if use paging it will throw errors because here will get footer row for paging so our row count will increase for that footer row paging we don’t have any checkboxes so input[0] this property will throw error to solve this problem we need to replace

 gvcheck.rows.length
to 
gvcheck.rows.length-1
Now it will work perfectly for paging enabled gridview also. Happy coding……

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

30 comments :

Anonymous said...

Thanks. This helps a lot to me.

I have one question. In my scenario, i have multiple checkbox columns when i'm looping in java script. It is loops on all with all the check boxs but i need to loop checkboxs for perticular column only.

Anonymous said...

all topics are very very very good.
Thanks for posting such articals.

Anonymous said...

this is not working in user control

Suresh Dasari said...

i hope you did some mistake please check your code it's working perfectly....

Pixy Digital said...

hi,

this code not working well. it produce an error..
pls help me how to resolve this error.

error is :

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Suresh Dasari said...

@Pixy Digital...
That error may be because of your gridview doesn't contain any value. Please check it once...

Anonymous said...

Gives error "Object required"

Unknown said...

Its worked. The note you have provided regarding paging was most helpful.
Thanks.

GopiKrishnan said...

First of all thanx for ur valuable information.I've a doubt,Suppose we've two inputs(say checkbox1 and checkbox2) then how will we able to distingush between the two....

BMG said...

use
document.getElementById('<%= gvdetails.ClientID %>');
instead of
document.getElementById('gvdetails');

it will be work in user control

Nitesh said...

sir i want to select rows when we check chekbox from childgridview from diffrent row

Nitesh said...

help me sir plz

John said...

Suresh,

Nice job. I couldn't get it to work and then I debugged and realized my page is running in an ASP:Content placeholder so I had to modify the gvcheck varaible to the following:

var gvcheck = document.getElementById('MainContent_MainContent_gvdetails');

Madhavi said...

hi, can is it be possible to help on same sample while the grid is having paging....?

mari said...

no vale tu porqueria...gracias

Anonymous said...

Getting error
Object reference not set to an instance of an object.

I am using master page in application.

Please provide solution of it
Thanks in advance

Anonymous said...

it is not working when checkbox present in last

Anonymous said...

send me at munait@gmail.com

Anonymous said...

its not working when we place all controls in update panel

Pls help

Unknown said...

it is not working. It is showing

'JavaScript runtime error: Unable to get property 'rows' of undefined or null reference'

Plz help

Anonymous said...

Really i like your articles.

Unknown said...

Your way of presentation is really wonderful.

Unknown said...

Hi It is working but display records are selected .i want all records are checked in gridview
Please help me

Anonymous said...

Perfect Solution, If you have gridview in update panel

function SelectAll(myvar) {
if (jQuery(myvar).attr('checked')) {
var checkboxes = jQuery(':checkbox', '#ContentGrid');
for (i = 0; i < checkboxes.length; i++) {
jQuery(checkboxes[i]).attr('checked', true)
}
}
else {
var checkboxes = jQuery(':checkbox', '#ContentGrid');
for (i = 0; i < checkboxes.length; i++) {
jQuery(checkboxes[i]).attr('checked', false)
}
}
}





Anonymous said...

Woriking good

Anonymous said...

Your articles are easy to learn..........

Anonymous said...

Thanx suresh.your coding is very simple and easy to understand.keep it up.

Anonymous said...

Thank u.. helps me a lots..thanx thanx thanx

Unknown said...

I need c# program plz!!

Unknown said...

screenshot is missing

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.