Click here to Skip to main content
11,629,393 members (65,579 online)
Click here to Skip to main content

Selecting multiple checkboxes inside a GridView control

, 3 Aug 2005 649.9K 1 147
Rate this:
Please Sign up or sign in to vote.
This article describes how you can select checkboxes inside a GridView control.

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 items from the GridView are already built in and you can use it through the design view. In this article, I will explain how you can select single as well as all the checkboxes which are inside a GridView control.

Selecting Checkboxes inside the GridView Control

GridView has a 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 a DataGrid control and want the same functionality, then please check out my article: Selecting multiple checkboxes inside a 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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

azamsharp
Web Developer
United States United States
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.

HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.

HighOnCoding.com www.HighOnCoding.com


My Blog:

Blog



Buy my iPhone app ABC Pop

You may also be interested in...

Comments and Discussions

 
QuestionGood Article Pin
Yakup Ünyılmaz25-Jun-15 21:42
professionalYakup Ünyılmaz25-Jun-15 21:42 
GeneralGood Article Pin
Alireza_136210-Apr-13 20:33
memberAlireza_136210-Apr-13 20:33 
QuestionI am not getting the check box value Pin
salamkudru16-Jan-13 20:23
membersalamkudru16-Jan-13 20:23 
AnswerRe: I am not getting the check box value Pin
salamkudru16-Jan-13 23:17
membersalamkudru16-Jan-13 23:17 
GeneralRe: I am not getting the check box value Pin
Anubha Bhatnagar22-Mar-13 2:14
memberAnubha Bhatnagar22-Mar-13 2:14 
GeneralRe: I am not getting the check box value Pin
salamkudru24-Mar-13 18:58
membersalamkudru24-Mar-13 18:58 
GeneralMy vote of 5 Pin
bluesathish20-Dec-12 17:23
memberbluesathish20-Dec-12 17:23 
GeneralMy vote of 5 Pin
manoj kumar choubey9-Feb-12 21:05
membermanoj kumar choubey9-Feb-12 21:05 
Questionhow can i count selected items and save them Pin
sparbery18-Aug-11 5:08
membersparbery18-Aug-11 5:08 
GeneralThanks! Pin
fundmf5-Aug-11 20:23
memberfundmf5-Aug-11 20:23 
Works fine. Thank you!
Generalthx Pin
Uzhn15-Apr-11 20:44
memberUzhn15-Apr-11 20:44 
GeneralUpdate Database Pin
pmosborne19-Jan-11 11:05
memberpmosborne19-Jan-11 11:05 
GeneralGridview Pin
ragini123021-Nov-10 20:46
memberragini123021-Nov-10 20:46 
GeneralMy vote of 1 Pin
adolfhardik3-Jun-10 23:21
memberadolfhardik3-Jun-10 23:21 
QuestionHow to Invoke Child Listview controls' Edit and Update Events Pin
renil64912-May-10 5:07
memberrenil64912-May-10 5:07 
QuestionMaster Page Pin
vicky_geek28-Apr-10 4:51
membervicky_geek28-Apr-10 4:51 
AnswerRe: Master Page Pin
azamsharp28-Apr-10 4:59
memberazamsharp28-Apr-10 4:59 
GeneralRe: Master Page Pin
vicky_geek28-Apr-10 19:17
membervicky_geek28-Apr-10 19:17 
GeneralAutoPlay From the List Pin
vondon17-Feb-10 8:56
membervondon17-Feb-10 8:56 
Generalit works great Pin
AnilMiLaN26-Nov-09 18:16
memberAnilMiLaN26-Nov-09 18:16 
QuestionHow to bring Old state to the checkboxes of the gridview control when the postback occurs Pin
Rajeshgut14-Oct-09 3:40
memberRajeshgut14-Oct-09 3:40 
AnswerRe: How to bring Old state to the checkboxes of the gridview control when the postback occurs Pin
azamsharp28-Apr-10 5:00
memberazamsharp28-Apr-10 5:00 
QuestionCan you do this without forms Pin
cheesehead9118229-Sep-09 7:50
membercheesehead9118229-Sep-09 7:50 
QuestionHow to select a checkbox with ctrl and click instead of click Pin
emily022823-Jun-09 9:15
memberemily022823-Jun-09 9:15 
GeneralNice article Pin
Donsw18-Apr-09 10:21
memberDonsw18-Apr-09 10:21 
GeneralPlz can u help Pin
Mehul_qaz16-Apr-09 3:52
memberMehul_qaz16-Apr-09 3:52 
Generalnice article Pin
kanza azhar12-Apr-09 3:37
memberkanza azhar12-Apr-09 3:37 
QuestionCheckboxes and GridView paging [modified] Pin
boqboq2-Mar-09 1:58
memberboqboq2-Mar-09 1:58 
AnswerRe: Checkboxes and GridView paging Pin
cUbeindaclUb5-Sep-11 23:37
membercUbeindaclUb5-Sep-11 23:37 
QuestionBeautiful!...How can I have 2 gridviews on a page and NOT have them control each other? Pin
Brian Fay9-Feb-09 11:51
memberBrian Fay9-Feb-09 11:51 
AnswerRe: Beautiful!...How can I have 2 gridviews on a page and NOT have them control each other? Pin
azamsharp11-Feb-09 7:50
memberazamsharp11-Feb-09 7:50 
GeneralExcelente Mi Amigo. Sos pero jodido. Pin
Luis Rangel4-Feb-09 6:34
memberLuis Rangel4-Feb-09 6:34 
GeneralAA - Awesome Azam! Pin
planetregin23-Dec-08 4:39
memberplanetregin23-Dec-08 4:39 
Generalgood Pin
Member 273824627-Aug-08 22:33
memberMember 273824627-Aug-08 22:33 
GeneralThank you for the great article Pin
jitendra v patil22-Aug-08 0:11
memberjitendra v patil22-Aug-08 0:11 
QuestionSessions questions Pin
Manigandanmax2cs16-Jul-08 0:31
memberManigandanmax2cs16-Jul-08 0:31 
QuestionHow to count checked checkbox while paging in the gridview? [modified] Pin
Member 408591513-Jun-08 1:46
memberMember 408591513-Jun-08 1:46 
QuestionGridView.DataSource = table; is not working with checkboxes in the GridView Pin
Member 459057921-Mar-08 22:57
memberMember 459057921-Mar-08 22:57 
QuestionHow to mark CheckBox as checked in DataGrid according to condition taken from database Pin
abhijeet.musale13-Mar-08 3:22
memberabhijeet.musale13-Mar-08 3:22 
General multiple column each one has checkall checkbox, I got it Pin
ab_dc21-Nov-07 2:16
memberab_dc21-Nov-07 2:16 
Questionmultiple column each one has checkall checkbox, how to??? Pin
ab_dc21-Nov-07 1:28
memberab_dc21-Nov-07 1:28 
GeneralThe checkbox returns false even if it checked [modified] Pin
Namrata110-Oct-07 23:37
memberNamrata110-Oct-07 23:37 
QuestionRe: The checkbox returns false even if it checked Pin
ab_dc23-Oct-07 2:01
memberab_dc23-Oct-07 2:01 
GeneralVery Good Article Pin
umay26-Oct-07 19:35
memberumay26-Oct-07 19:35 
GeneralRe: Very Good Article Pin
ab_dc28-Oct-07 1:06
memberab_dc28-Oct-07 1:06 
GeneralRe: Very Good Article Pin
riteshms26-Feb-08 23:45
memberriteshms26-Feb-08 23:45 
GeneralMulti column Check box list Pin
T.Ashraf15-Aug-07 8:54
memberT.Ashraf15-Aug-07 8:54 
GeneralUsing similar to update multiple rows Pin
beish19-Aug-07 23:06
memberbeish19-Aug-07 23:06 
GeneralBrilliant! Pin
thund3rstruck6-Jun-07 11:36
memberthund3rstruck6-Jun-07 11:36 
GeneralThanks a lot azamsharp Pin
tariqbk19-May-07 8:14
membertariqbk19-May-07 8:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150723.1 | Last Updated 3 Aug 2005
Article Copyright 2005 by azamsharp
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid