Selecting Checkboxes inside GridView Control
By AzamSharp
Views: 31643

 

Introduction:

GridView is a new data bound control introduced by Microsoft in Visual Studio.NET 2005. Most of the operations like sorting, paging and selecting item from the GridView is already built in and you can use it through the design view. In this article I will explain that how you can select single as well as all the checkboxes which are inside the GridView control.

Selecting Checkboxes inside the GridView Control:

GridView has CheckboxField column which maps the checkbox to a field in the database. In this article we won't be using that, we will make a checkbox in a template column. Simply add a asp:checkbox control in the item template of the GridView control. If you are working with Datagrid control and want the same functionality than please check out my article Selecting Checkboxes inside the Datagrid control.

The html code looks something like this:

 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="PersonID" DataSourceID="mySource" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="PersonID" HeaderText="PersonID" InsertVisible="False"
ReadOnly="True" SortExpression="PersonID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>

Now in the button click event write this code:

// StringBuilder object

StringBuilder str = new StringBuilder();

// Select the checkboxes from the GridView control

for (int i = 0; i < GridView1.Rows.Count; i++)

{

GridViewRow row = GridView1.Rows[i];

bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

if (isChecked)

{

// Column 2 is the name column

str.Append(GridView1.Rows[i].Cells[2].Text);

}

}

// prints out the result

Response.Write(str.ToString());

 

The code above just iterates through the GridView and selects the checked checkboxes. Later it appends the selected value to a StringBuilder object. In order to use StringBuilder you will need to add the System.Text namespace.   

Making a CheckAll functionality:

To add a check all functionality in the GridView simply add a html checkbox to the header template of the checkbox column.

 <HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>

SelectAllCheckboxes JavaScript method:

<script language=javascript>

function SelectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox

var oItem = spanChk.children;

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

xState=theBox.checked;

elm=theBox.form.elements;

for(i=0;i<elm.length;i++)

if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)

{

//elm[i].click();

if(elm[i].checked!=xState)

elm[i].click();

//elm[i].checked=xState;

}

}

</script>

 

This is it. I hope you like the article, happy coding!

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Doesn't work if post back
Name: Vinh
Date: 1/26/2007 11:33:05 AM
Comment:
Just doesn't work on the button click event if it does a postback. Values are gone. Thanks anyway.
Subject: Check this article
Name: AzamSharp
Date: 1/26/2007 6:47:16 PM
Comment:
Hi,

You can check out the following article on AspAlliance:

http://aspalliance.com/774_Maintaining_State_of_CheckBoxes_While_Paging_in_a_GridView_Control
Subject: Any Suggestions?
Name: Pouyan
Date: 2/5/2007 1:47:30 AM
Comment:
I tried it but it did not work for me.
This line always returns a false value :

bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

Any suggestions?

Cheers,
Subject: RE:
Name: AzamSharp
Date: 2/8/2007 8:46:27 AM
Comment:
Make sure that you are not using the CheckBoxField column. You need to use TemplateField column.
Subject: Greate Work
Name: Kiran
Date: 2/26/2007 3:14:13 AM
Comment:
Its Working Greate for me

Thanks A Lot

Subject: checkbox in gridview
Name: subitha.M.S
Date: 2/27/2007 8:48:38 PM
Comment:
Hi,
Thanks alot.This code is helped me to solve my problem.please use the templatefield to add checkbox to gridview
Subject: Article
Name: saroj
Date: 3/1/2007 1:29:57 AM
Comment:
A good Stufff
Subject: Selecting Checkboxes inside the GridView Control:
Name: Chirag Shah
Date: 3/8/2007 1:51:49 AM
Comment:
Hi,

The article mentioned in the subject line does not work it states that "Object reference not set to an instance of an object."


at the following lines in the article

"GridViewRow row = GridView1.Rows[i];

bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

"

Do reply back


Thanks and Regards

Chirag Shah
Subject: Select all checkboxes in gridview
Name: santosh
Date: 3/11/2007 3:57:00 AM
Comment:
i have two gridviews in a page and both has selectall checkboxes. How can I make each of them independent of the other. Right now checkboxes in both gridviews gets selected and deselected together
Subject: Not working
Name: Rajesh Kumar
Date: 3/12/2007 11:55:18 AM
Comment:
Doesn't work on the button click event if it does a postback. Values are gone.
I am using TemplateField column.







Thanks,
Rajesh
Subject: Not working
Name: Rajesh Kumar
Date: 3/12/2007 11:58:04 AM
Comment:
Just a comment on previous feedback that I sent:

"I am also not using Paging"
Subject: RE: Not Working
Name: AzamSharp
Date: 3/12/2007 8:33:18 PM
Comment:
I suggest that you check out the following article. The article talks about maintaining the checkboxes while paging but it will also be suitable for your scenario.

http://aspalliance.com/774_Maintaining_State_of_CheckBoxes_While_Paging_in_a_GridView_Control
Subject: RE: Two GridViews
Name: AzamSharp
Date: 3/12/2007 8:37:11 PM
Comment:
Santosh, if you have two GridViews then you can use regular expression to match the checkboxes. Check out the following article which performs this action using regular expressions.

http://gridviewguy.com/ArticleDetails.aspx?articleID=228

Subject: RE: Chirag Shah
Name: AzamSharp
Date: 3/12/2007 8:44:21 PM
Comment:
Hi Chirag Shah,

Which line is giving you the problem? Use debugger?
Subject: checkbox
Name: victor
Date: 3/21/2007 12:38:01 PM
Comment:
Very nice job.
Subject: GridView checkbox
Name: Jun
Date: 3/23/2007 10:27:37 AM
Comment:
your code rocks, esp. the js

worked great for me with a bit of refactoring.

thanx
Subject: good article
Name: supraja
Date: 3/27/2007 2:59:50 AM
Comment:
thank u AzamSharp
this article heped me alot.
Subject: code helped
Name: Nasim Kazi S
Date: 4/4/2007 4:50:49 AM
Comment:
Hey, this code was really helpful..
i have seen many articles of urs in codeproject too..
Keep up the good work..

KUDOS..
Subject: Problem with checkboxes outside GridView
Name: Juliano Nunes
Date: 4/12/2007 6:08:46 AM
Comment:
There is just a problem in my case, this code changes the checked state for every checkbox on the page, even those outside the GridView.
Subject: problem in Selecting Checkboxes inside GridView Control
Name: sabya
Date: 4/14/2007 2:18:06 AM
Comment:
hi all,
I have used the same template field for checkbox but after selecting the chekbox its not showing true value.so i am not getting the control of the checked box.
kindly help.
thanks,
sabya
Subject: Thanks
Name: Saurabh Tripathi
Date: 4/25/2007 12:25:37 AM
Comment:
Nics Post I had your this post in code project also...
thanks for very easy approach
Subject: Thank you
Name: Mitesh
Date: 5/2/2007 9:51:29 PM
Comment:
the article was very helpful .. can anybody help me with retaining values while postback in gridview
Subject: select All Checkbox javascript
Name: Mukesh Variya
Date: 5/21/2007 3:45:03 AM
Comment:
Hi,

I found this script from google search engine.

This is really good script which I am looking for.

Thankx for Helping.

http://mukeshvariya.blogspot.com
Subject: check all issue..
Name: srikanth
Date: 5/22/2007 11:37:47 PM
Comment:
When clicking on SELECT ALL, Make sure all the messages in all the pages gets selected, not just the current page in gridview.

Any suggestions?
Subject: Update DataTable
Name: Marcel
Date: 5/24/2007 2:25:00 PM
Comment:
Hi, congratulations for you article!

I'm having a problem with my GridView. I'm working with groups in my grid(I saw a article about grouping in Grid View using GridViewHelper class) and have a templateField with a CheckBox.

I need register in my DataBase how document's of the client was delivered(need register the not delivered too). I created a method with a for, using with condition mygrid.rows.count but, I was unhappy because my method lost de index of de row and don't register the data.

Could you help me?
Subject: Help
Name: shyam
Date: 5/25/2007 1:00:39 PM
Comment:
I tried it but it did not work for me.
This line always returns a false value :

bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

Any suggestions?
Subject: Thank you
Name: Nick
Date: 6/5/2007 6:34:27 AM
Comment:
goood!
Subject: Help
Name: DEEPAK GUPTA
Date: 7/4/2007 7:29:27 AM
Comment:
Hello Friends
I am new to JavaScript
I am using the above code for selecting checkboxes inside the GridView COntrol But whats going wrong is that i have two GridView Controls inside my Form and so if i check any of the checkbox in any GridView Control,all of the checkbox gets selected. I want that only those checkbox gets selected which belongs to that GridView Control only.

Thanx
Bye
Subject: Always returning false?
Name: Wayne
Date: 7/16/2007 10:42:53 AM
Comment:
I had the issue where my checkbox values were always returning false upon postback. After some head-scratching, I remembered that my page_load event would always fire first, then any click event procedure would fire.

I resolved this by wrapping the page_load code within a if (!page.ispostback) and now I can get the appropriate 'true' values off the checked property I was expecting.

I just love working with other peoples code....hope this will help some people out there. Thanks for the article Azam!

Cheers!

Wayne
www.diggityhost.com - Buy your domains for less here!
Subject: THANKS
Name: ashish
Date: 7/17/2007 5:32:50 AM
Comment:
THANKS a million
Subject: Selecting Checkboxes inside GridView Control
Name: Ravi
Date: 7/25/2007 9:02:58 AM
Comment:
Hi Md. Azam ,
This is nice and use ful article .
Thanks
Ravi
Subject: In javascript how to get spanChk
Name: amal
Date: 8/14/2007 2:29:52 AM
Comment:
In javascript how to get spanChk?
Subject: RE: How to get spanckh
Name: AzamSharp
Date: 8/14/2007 8:38:50 AM
Comment:
Hi Amal,

Not sure if I understand your problem correctly.

Subject: Regrding this code
Name: Amitsoam
Date: 8/27/2007 12:24:04 AM
Comment:
It working good , i would like to know if i will check indiual check box then it is not working.........
Subject: good yar
Name: Abdul Qadar
Date: 8/29/2007 4:24:44 AM
Comment:
i just want to sya k

tu Cheeeeta ha yar.
Subject: simply its great
Name: Anju
Date: 9/8/2007 5:06:14 AM
Comment:
Really it makes my codind so easy so thanks and keep going on like this....
Subject: Change the apperance
Name: Pranav
Date: 10/7/2007 8:33:42 AM
Comment:
Could you guide me as to how to change the row apperance when the checkbox/es are selected. I m a bit new to javascript....
Subject: all checked are false !!
Name: Gersy
Date: 10/23/2007 5:33:06 AM
Comment:
Hello basha, thanks a lot
but , it selected ok
but when checking it's value , it gives me false even checked or un-checked
so is there any update????
plz reply this
Subject: Works!
Name: Lúcia
Date: 10/26/2007 4:18:31 AM
Comment:
Thanks!! It worked!!


Subject: check box with gridview
Name: vijayt kumar
Date: 11/4/2007 10:12:55 AM
Comment:
its very help full to and its working well
but i have a requirement like this..
when a check box in a gridview is selected, i need to get the corresponding row index.plz give me a soln with out using a for each statement. use event bubling.raise checkbox_checked event to the parent gridview and do a task.
plz give me a soln and send it to my mail id.
thanks
Subject: RE: vijayt kumar
Name: AzamSharp
Date: 11/6/2007 9:41:46 AM
Comment:
Hi Vijayt Kumar

You can check out the following blog entry:

http://geekswithblogs.net/azamsharp/archive/2006/01/10/65433.aspx
Subject: checkbox in gridview
Name: Ketak Mahajan
Date: 12/2/2007 11:50:10 PM
Comment:
hi, i used the code. but there is a problem

the following line always return false.

bool result = ((CheckBox)row.FindControl("chkSelect")).Checked;

even though i have used the template feild for this.

Any suggestion. please
Subject: Thx - nice code
Name: Dimitris
Date: 1/15/2008 3:54:10 AM
Comment:
Thank you, especially for the CheckAll client side code. Nice.
Subject: thanx!!!
Name: andrea
Date: 2/4/2008 1:20:21 AM
Comment:
thanx a lot!

i always saw checkbox as not checked, also if it was.

using "if not page.ispostback then" in the page load, now it works!!

great!! i was going crazy!
Subject: FeedBack
Name: Hemadri
Date: 2/8/2008 1:16:20 AM
Comment:
Excellent Article on Gridview
Thank You
Subject: Error
Name: sunilkumar
Date: 2/14/2008 2:55:27 AM
Comment:
GridViewRow row = GridView1.Rows[i];

bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;

str.Append(Gridview1.Rows[i].Cells[2].Text);

some error occur at this
I have very urgent this code pls find the error and send to my mail id

code is not working
Subject: Nice Article
Name: Srinivas
Date: 3/8/2008 9:53:09 PM
Comment:
Nice one.. I liked the javascript code to check all the check boxes
Subject: Selecting Checkboxes inside the GridView Control:
Name: Vijay
Date: 3/18/2008 7:24:29 PM
Comment:
Thank you very much
Subject: hi..thank you!!
Name: Amol Kagde
Date: 4/13/2008 9:42:18 PM
Comment:
realy this article is helpful!

Thank you!



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008