Click here to Skip to main content
6,295,667 members and growing! (14,415 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Data     Beginner

Adding a CheckBox Column to a DataGrid

By Dan_P

Shows how to add a checkbox column to a datagrid
C#, Windows, .NET 1.0, ASP.NET, Visual Studio, Dev
Posted:29 May 2003
Views:187,027
Bookmarked:74 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
24 votes for this article.
Popularity: 5.88 Rating: 4.26 out of 5
3 votes, 13.0%
1

2
1 vote, 4.3%
3
6 votes, 26.1%
4
13 votes, 56.5%
5

Sample Image - DataGridCheckBoxCol.gif

Introduction

A recent project I was working on required a user to select a number of options from a list. Instead of using a mulit-select list box which didn't really fit into the design of the site we decided to make a reusable control that would add a checkbox to a DataGrid.

Using the code

To use the checkbox column in a DataGrid it's simply a matter of registering the tag at the top of the page:

<%@ Register TagPrefix="chkbox" Namespace="DataGridControls" 
    Assembly="DataGridCheckbox" %>

Then to add the checkbox column to the DataGrid:

<asp:DataGrid ID="dgTestGrid" Runat="server" AutoGenerateColumns=True 
    border="0" width="50%">
   <Columns>
   <chkbox:CheckBoxColumn/>
   </Columns>
  </asp:DataGrid>

The CheckBoxColumn class is pretty straight forward:

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DataGridControls
{
 /// <summary>

 /// CheckBoxColumn Derives from DataGrid Column

 /// </summary>

 public class CheckBoxColumn : DataGridColumn
 {
    public CheckBoxColumn(): base()
      {
      }
  
      public override void InitializeCell(TableCell cell, 
        int columnIndex, ListItemType itemType) 
      {
           //let the base class initialize the cell

           base.InitializeCell(cell, columnIndex, itemType);



           //we don't want to add a checkbox to the header.

           if(    itemType == ListItemType.EditItem || 
            itemType == ListItemType.Item || 
            itemType == ListItemType.AlternatingItem || 
            itemType == ListItemType.SelectedItem){

                HtmlInputCheckBox checkbox = new HtmlInputCheckBox();
                //assign an ID that we can use to find the control later

                checkbox.ID = "checkboxCol";
                cell.Controls.Add(checkbox);
           }
      }
      public Int32[] SelectedIndexes 
      {
           get 
           {
                ArrayList selectedIndexList = new ArrayList();
                //iterate each DataGridItem and find our checkbox

                foreach( DataGridItem item in this.Owner.Items ) 
                {
                     HtmlInputCheckBox chkBox = 
                        (HtmlInputCheckBox) item.FindControl("checkboxCol");
     
                     //If it's selected then add it to our ArrayList

                     if ( chkBox != null && chkBox.Checked )  
                     {
                          selectedIndexList.Add( item.ItemIndex );
                     } 
     
                }
                return (Int32[])selectedIndexList.ToArray(typeof( 
                        System.Int32 ) );
           }
      }
      public object[] SelectedDataKeys 
      {
           get 
           {
                //Just iterate each of the selectedindexes and 

                //match it up to the datakey field

                ArrayList dataKeyList = new ArrayList();
                //make sure the datakeys have some values

                if(this.Owner.DataKeys.Count > 0)
                {
                     foreach( Int32 selectedIndex in SelectedIndexes ) 
                     {
     
                          object DataKey = 
                              (this.Owner.DataKeys[selectedIndex].ToString());
                          dataKeyList.Add(DataKey);
                     }
                }
                return (object[])dataKeyList.ToArray(typeof( object ) );
           }
   
      }
   }
}

The class exposes 2 properties: 

  • SelectedDataKeys: Returns an ArrayList with the DataKey values
  • SelectedIndexes: Returns an Int32[] with the selectedIndex values

To find out which checkbox has been selected:

//On our button's Onclick


protected void btnSubmit_Click(object sender, EventArgs e)
  {
   //Get our checkboxcolumn, we know it's position is 0

   CheckBoxColumn chkbox = (CheckBoxColumn) dgTestGrid.Columns[0];
   
   foreach(object datakeyfield in chkbox.SelectedDataKeys)
   {
    Response.Write(datakeyfield.ToString() + "<br>");
   }
  }

That's pretty much it, the DataKeyField of the DataGrid can be of any type. The sample I've included binds a DataTable to the DataGrid, you can change the DataKeyField from "ID" (int) to "Name" (string) to see the code working with different types.

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

Dan_P


Member
I've been programming for a few years now. I blog regularly at httpcode.
Occupation: Web Developer
Location: Australia Australia

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 24 of 24 (Total in Forum: 24) (Refresh)FirstPrevNext
Generalbrowse button PinmemberMember 44423502:30 11 Apr '08  
GeneralI can't load the project PinmemberGFJ6:12 16 Jul '07  
GeneralThe same but for VB.NET PinmemberTheSilentman4:47 14 Feb '07  
GeneralWhat will happen if more one page data will it work properly Pinmember22:06 21 Jan '07  
GeneralWhat about TemplateColumn PinmemberSenFo9:35 9 Jan '06  
GeneralRe: What about TemplateColumn Pinmemberjeganji19:45 14 Dec '06  
GeneralRe: What about TemplateColumn Pinmembererax dan23:17 13 Aug '08  
GeneralModified Code for Server-Side Select-DeselectAll Pinmembersikemullivan10:11 15 Oct '05  
GeneralRe: Modified Code for Server-Side Select-DeselectAll Pinmemberlowlandr6:01 30 Dec '05  
GeneralRe: Modified Code for Server-Side Select-DeselectAll PinmemberSilverSabre5:41 18 Nov '08  
GeneralError with Assembly Pinmembersikemullivan11:56 12 Oct '05  
General2 CHECKBOXCOLUMN in a Datagrid PinmemberOlog-hai11:08 29 Apr '05  
GeneralRe: 2 CHECKBOXCOLUMN in a Datagrid PinmemberSilverSabre1:18 18 Nov '08  
GeneralData type undefined PinmemberDustin Boston11:14 12 Jan '05  
GeneralCheckbox in datagrid Pinmemberfredo_lefran0:35 4 Jan '05  
Generalcheckbox initial value? PinmemberJ_T_C12:04 29 Jun '04  
GeneralRe: checkbox initial value? PinmemberSukim0:30 15 Aug '04  
GeneralRe: checkbox initial value? PinmemberSukim2:15 15 Aug '04  
Generalthe example will show error in VS.net 2003 Pinmemberhardyhe18:01 9 May '04  
GeneralRe: the example will show error in VS.net 2003 Pinmemberjsnook9:12 18 Jun '04  
GeneralSelect/Deselect All Pinmemberpeterwi13:43 19 Dec '03  
Generala bug .... Pinmembertopcn9:07 22 Jun '03  
GeneralRe: a bug .... Pinmemberjsnook8:03 18 Jun '04  
GeneralRe: a bug .... PinmemberCanz23:18 3 Jan '05  

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

PermaLink | Privacy | Terms of Use
Last Updated: 29 May 2003
Editor: Nishant Sivakumar
Copyright 2003 by Dan_P
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project