Click here to Skip to main content
6,821,293 members and growing! (18,834 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

Selecting multiple checkboxes inside a GridView control

By azamsharp

This article describes how you can select checkboxes inside a GridView control.
C#, Javascript, HTML, Windows, .NET2.0, ASP.NET, WebForms, VS2005, Dev
Posted:3 Aug 2005
Views:282,354
Bookmarked:110 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
57 votes for this article.
Popularity: 7.87 Rating: 4.48 out of 5
2 votes, 3.5%
1
2 votes, 3.5%
2
4 votes, 7.0%
3
7 votes, 12.3%
4
42 votes, 73.7%
5

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

About the Author

azamsharp


Member
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

Occupation: Web Developer
Location: United States United States

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 68 (Total in Forum: 68) (Refresh)FirstPrevNext
Generalit works great PinmemberAnilMiLaN19:16 26 Nov '09  
GeneralHow to bring Old state to the checkboxes of the gridview control when the postback occurs PinmemberRajeshgut4:40 14 Oct '09  
GeneralCan you do this without forms Pinmembercheesehead911828:50 29 Sep '09  
QuestionHow to select a checkbox with ctrl and click instead of click Pinmemberemily022810:15 23 Jun '09  
GeneralNice article PinmemberDonsw11:21 18 Apr '09  
GeneralPlz can u help PinmemberMehul_qaz4:52 16 Apr '09  
Generalnice article Pinmemberkanza azhar4:37 12 Apr '09  
QuestionCheckboxes and GridView paging [modified] Pinmemberboqboq2:58 2 Mar '09  
QuestionBeautiful!...How can I have 2 gridviews on a page and NOT have them control each other? PinmemberBrian Fay12:51 9 Feb '09  
AnswerRe: Beautiful!...How can I have 2 gridviews on a page and NOT have them control each other? Pinmemberazamsharp8:50 11 Feb '09  
GeneralExcelente Mi Amigo. Sos pero jodido. PinmemberLuis Rangel7:34 4 Feb '09  
GeneralAA - Awesome Azam! Pinmemberplanetregin5:39 23 Dec '08  
Generalgood PinmemberMember 273824623:33 27 Aug '08  
GeneralThank you for the great article Pinmemberjitendra v patil1:11 22 Aug '08  
JokeGreat article - simple and concise! PinmemberMark Abraham11:41 8 Aug '08  
QuestionSessions questions PinmemberManigandanmax2cs1:31 16 Jul '08  
QuestionHow to count checked checkbox while paging in the gridview? [modified] PinmemberMember 40859152:46 13 Jun '08  
QuestionGridView.DataSource = table; is not working with checkboxes in the GridView PinmemberMember 459057923:57 21 Mar '08  
GeneralHow to mark CheckBox as checked in DataGrid according to condition taken from database Pinmemberabhijeet.musale4:22 13 Mar '08  
General multiple column each one has checkall checkbox, I got it Pinmemberab_dc3:16 21 Nov '07  
Generalmultiple column each one has checkall checkbox, how to??? Pinmemberab_dc2:28 21 Nov '07  
GeneralThe checkbox returns false even if it checked [modified] PinmemberNamrata10:37 11 Oct '07  
QuestionRe: The checkbox returns false even if it checked Pinmemberab_dc3:01 23 Oct '07  
GeneralVery Good Article Pinmemberumay20:35 26 Oct '07  
GeneralRe: Very Good Article Pinmemberab_dc2:06 28 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 3 Aug 2005
Editor: Smitha Vijayan
Copyright 2005 by azamsharp
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project