Click here to Skip to main content
15,885,546 members
Articles / Web Development / HTML

Selecting Multiple checkboxes inside a GridView Control

Rate me:
Please Sign up or sign in to vote.
4.66/5 (83 votes)
3 Aug 20051 min read 817.4K   148   89
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.NET
<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:

C#
// 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.

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

SelectAllCheckboxes JavaScript method:

JavaScript
<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!

History

  • 3rd August, 2005: Initial version

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.


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
JokeGreat article - simple and concise! Pin
Mark Abraham8-Aug-08 10:41
Mark Abraham8-Aug-08 10:41 
QuestionSessions questions Pin
Manigandanmax2cs16-Jul-08 0:31
Manigandanmax2cs16-Jul-08 0:31 
QuestionHow to count checked checkbox while paging in the gridview? [modified] Pin
Member 408591513-Jun-08 1:46
Member 408591513-Jun-08 1:46 
QuestionGridView.DataSource = table; is not working with checkboxes in the GridView Pin
Member 459057921-Mar-08 22:57
Member 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
abhijeet.musale13-Mar-08 3:22 
General multiple column each one has checkall checkbox, I got it Pin
ab_dc21-Nov-07 2:16
ab_dc21-Nov-07 2:16 
Questionmultiple column each one has checkall checkbox, how to??? Pin
ab_dc21-Nov-07 1:28
ab_dc21-Nov-07 1:28 
GeneralThe checkbox returns false even if it checked [modified] Pin
Namrata110-Oct-07 23:37
Namrata110-Oct-07 23:37 
Even wen I hav checked the check box it returns false.. I am pasting the code here....

Any help would be strongly appreciated.

I need it urgently guys..!!!


for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
bool check= ((CheckBox)row.FindControl("chkselect")).Checked;
if (check)
{
string str=GridView1.Rows[i].Cells[1].Text;
Response.Write(str);
}


}

Also the DataItemIndex is zero..

I dont know how to resolve the problem since i am a beginner in asp.net please help me out

Regards,
Namrata.


-- modified at 5:43 Thursday 11th October, 2007
QuestionRe: The checkbox returns false even if it checked Pin
ab_dc23-Oct-07 2:01
ab_dc23-Oct-07 2:01 
GeneralVery Good Article Pin
RUmayaldevi26-Oct-07 19:35
RUmayaldevi26-Oct-07 19:35 
GeneralRe: Very Good Article Pin
ab_dc28-Oct-07 1:06
ab_dc28-Oct-07 1:06 
GeneralRe: Very Good Article Pin
riteshms26-Feb-08 23:45
riteshms26-Feb-08 23:45 
GeneralMulti column Check box list Pin
T.Ashraf15-Aug-07 8:54
T.Ashraf15-Aug-07 8:54 
GeneralUsing similar to update multiple rows Pin
beish19-Aug-07 23:06
beish19-Aug-07 23:06 
GeneralBrilliant! Pin
thund3rstruck6-Jun-07 11:36
thund3rstruck6-Jun-07 11:36 
GeneralThanks a lot azamsharp Pin
tariqbk19-May-07 8:14
tariqbk19-May-07 8:14 
GeneralStill problem in checkbox in gridview Pin
jigarchaudhari19-Jan-07 21:32
jigarchaudhari19-Jan-07 21:32 
GeneralRe: Still problem in checkbox in gridview Pin
vijaymodi_8119-Jan-07 23:49
vijaymodi_8119-Jan-07 23:49 
GeneralRe: Still problem in checkbox in gridview Pin
azamsharp20-Jan-07 11:53
azamsharp20-Jan-07 11:53 
GeneralRe: Still problem in checkbox in gridview Pin
jigarchaudhari21-Jan-07 18:32
jigarchaudhari21-Jan-07 18:32 
GeneralRe: Still problem in checkbox in gridview Pin
Namrata111-Oct-07 0:02
Namrata111-Oct-07 0:02 
GeneralRe: Still problem in checkbox in gridview Pin
jigarchaudhari21-Jan-07 18:34
jigarchaudhari21-Jan-07 18:34 
QuestionI do checkbox selection in gridview but it gives me a false value Pin
jigarchaudhari19-Jan-07 0:48
jigarchaudhari19-Jan-07 0:48 
AnswerRe: I do checkbox selection in gridview but it gives me a false value Pin
vijaymodi_8119-Jan-07 1:47
vijaymodi_8119-Jan-07 1:47 
QuestionRe: I do checkbox selection in gridview but it gives me a false value Pin
boyfromchina16-Jun-07 20:59
boyfromchina16-Jun-07 20:59 

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

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