Click here to Skip to main content
15,879,474 members
Articles / Web Development / ASP.NET
Article

Adding a CheckBox Column to a DataGrid

Rate me:
Please Sign up or sign in to vote.
4.55/5 (28 votes)
29 May 2003 325.4K   4.3K   94   26
Shows how to add a checkbox column to a datagrid

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:

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

Then to add the checkbox column to the DataGrid:

ASP.NET
<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:

C#
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:

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


Written By
Web Developer
Australia Australia
I've been programming for a few years now. I blog regularly at httpcode.

Comments and Discussions

 
GeneralPretty handy Pin
JBress8-Jun-11 3:56
JBress8-Jun-11 3:56 
GeneralC#Net2003 - Window Application Add CheckBox In DataGrid Pin
TeeLeong4-Nov-09 8:56
TeeLeong4-Nov-09 8:56 
Generalbrowse button Pin
KSagar11-Apr-08 1:30
KSagar11-Apr-08 1:30 
GeneralI can't load the project Pin
GFJ16-Jul-07 5:12
GFJ16-Jul-07 5:12 
GeneralThe same but for VB.NET Pin
TheSilentman14-Feb-07 3:47
TheSilentman14-Feb-07 3:47 
QuestionWhat will happen if more one page data will it work properly Pin
Member 75098521-Jan-07 21:06
Member 75098521-Jan-07 21:06 
What will happen if more one page data will it work properly
QuestionWhat about TemplateColumn Pin
SenFo9-Jan-06 8:35
SenFo9-Jan-06 8:35 
AnswerRe: What about TemplateColumn Pin
jeganji14-Dec-06 18:45
jeganji14-Dec-06 18:45 
GeneralRe: What about TemplateColumn Pin
erax dan13-Aug-08 22:17
erax dan13-Aug-08 22:17 
GeneralModified Code for Server-Side Select-DeselectAll Pin
SikeMullivan15-Oct-05 9:11
SikeMullivan15-Oct-05 9:11 
GeneralRe: Modified Code for Server-Side Select-DeselectAll Pin
lowlandr30-Dec-05 5:01
lowlandr30-Dec-05 5:01 
GeneralRe: Modified Code for Server-Side Select-DeselectAll Pin
SilverSabre18-Nov-08 4:41
SilverSabre18-Nov-08 4:41 
GeneralError with Assembly Pin
SikeMullivan12-Oct-05 10:56
SikeMullivan12-Oct-05 10:56 
General2 CHECKBOXCOLUMN in a Datagrid Pin
huguesgauthier29-Apr-05 10:08
huguesgauthier29-Apr-05 10:08 
GeneralRe: 2 CHECKBOXCOLUMN in a Datagrid Pin
SilverSabre18-Nov-08 0:18
SilverSabre18-Nov-08 0:18 
GeneralData type undefined Pin
Dustin Boston12-Jan-05 10:14
Dustin Boston12-Jan-05 10:14 
GeneralCheckbox in datagrid Pin
fredo_lefran3-Jan-05 23:35
fredo_lefran3-Jan-05 23:35 
Questioncheckbox initial value? Pin
J_T_C29-Jun-04 11:04
J_T_C29-Jun-04 11:04 
AnswerRe: checkbox initial value? Pin
Sukim14-Aug-04 23:30
Sukim14-Aug-04 23:30 
GeneralRe: checkbox initial value? Pin
Sukim15-Aug-04 1:15
Sukim15-Aug-04 1:15 
Generalthe example will show error in VS.net 2003 Pin
hardyhe9-May-04 17:01
hardyhe9-May-04 17:01 
GeneralRe: the example will show error in VS.net 2003 Pin
jsnook18-Jun-04 8:12
jsnook18-Jun-04 8:12 
GeneralSelect/Deselect All Pin
peterwi19-Dec-03 12:43
peterwi19-Dec-03 12:43 
Generala bug .... Pin
topcn22-Jun-03 8:07
topcn22-Jun-03 8:07 
GeneralRe: a bug .... Pin
jsnook18-Jun-04 7:03
jsnook18-Jun-04 7:03 

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.