Saturday, February 21, 2009

Selecting all check boxes in a gridview control

Please visit my new Web Site

By using client script selecting all check boxes in a gridview control is a most common task. Here i am trying to show an example for begginers how we can provide this functionality into our pages to enhance user experience. Here i am using a tempalte column to add both header checkbox & rows checkbox in the gridview. When user click on the header checkbox then a javascript method will be invoked To select/deselect all checkboxes inside the gridview rows depends on header checkbox checked property. Like:

So to do that at first i need to add a gridview control in my aspx page. Code like:
<b>List of suppliers:</b>

<asp:GridView runat="server" ID="gvEdit" DataKeyNames="ID" AutoGenerateColumns="false" >

<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox runat="server" ID="chk"/></ItemTemplate>
<input id="chkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" runat="server" type="checkbox" value="" />

<asp:BoundField DataField="Code" HeaderText="Code" ></asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name" ></asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address"></asp:BoundField>
<asp:BoundField DataField="Contact" HeaderText="Contact no"></asp:BoundField>


Now gridview control added in our page. So now we can populate our gridview from serverside code. I hope its not necessary to provide server side code in this post.

Now to acheive our goal we need to do just adding a javascript function. Add the following javascript function to select all check boxes within a GridView.

function GridSelectAllColumn(spanChk, chkName)

var oItem = spanChk.children;
var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0]; xState=theBox.checked;

for(i=0;i -1)
if(elm[i].checked != xState)
}//end for

}//end func

Hope now it will work perfectly. For further study you can try with jquery :)


Anonymous said...

Please help me ... i'm applied many codes even your code but there an error in all code show me .... the error is when click on delete button the tick hide from check box without Delete Operation ....

Shawpnendu said...

Did you bind the GridView in Page_Load method. If so then make sure that all codes wrapped by like:
// Your code goes here.


Let me know if still not resolved.

Want to say something?

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash