Click here to Skip to main content
12,251,121 members (37,302 online)
Click here to Skip to main content
Add your own
alternative version


204 bookmarked

Adding a CheckBox column to your DataGrid

, 3 Sep 2002 CPOL
Rate this:
Please Sign up or sign in to vote.
A CheckBox column that is can be used and bound in a DataGrid

Sample Image - checkgrid.jpg


There are many articles that explain how to add controls to a DataGrid that can be used to represent and edit data in a format other than a common EditBox, however they all appear to require the programmer to edit the html in the .aspx page(s) rather than use code held solely in the .cs Codebehind files. I have in the past had to implement many different controls that can be used to represent and edit controls within a DataGrid and here I will demonstrate the CheckBox template column with bound CheckBoxes as it is one of the simplest but the the most used control other then the EditBox, and is used to edit fields that are of the boolean type.

ITemplate implementation

Before we can implement the class that will be used as a column within our DataGrid, a class that derives from ITemplate will need to be created that can be used for representing and or editing the data within the grid. In most cases a seperate class will need to be defined for displaying and editing, eg containing a label control or an edit box control. Fortunately we can use the same control, a CheckBox, to represent the boolean state as well as edit it.

public CheckBoxItem(bool editable)
    readOnly = (editable==true)?false:true;

Handling the DataBinding event

Because the CheckBox control is to represent data that is held in the DataGrid then it will need to handle the DataBinding event, which will be called once for each row in the DataGrid. This can be set up in the InstantiateIn method implementation which is the one and only method of the ITemplate interface.

void ITemplate.InstantiateIn(Control container)
    CheckBox box = new CheckBox();
    box.DataBinding += new EventHandler(this.BindData);

Processing the DataBinding event

The handler for the DataBinding event is used to set the state of the control depending on the data within the underlying DataGrid as well as set the editable state depending on whether it is being used to view the data or edit the data.

public void BindData(object sender, EventArgs e)
    CheckBox box = (CheckBox) sender;
    DataGridItem container = (DataGridItem) box.NamingContainer;
    box.Checked = false;
    box.Enabled = (readOnly == true) ? false:true;
    string data = ((DataRowView) container.DataItem)[dataField].ToString();
    Type type = ((DataRowView)
    if (data.Length>0)
        switch (type.ToString())
        case "System.Boolean":
            if ( data == "True")
                box.Checked = true;

CheckBox Template Column

The class that will be used as the column in our DataGrid will be derived from the System.Web.UI.WebControls.TemplateColumn class. We add objects of the above ITemplate implementation class to the ItemTemplate property, for display, and EditItemTemplate property, for editing.

public CheckBoxColumn()
    // set the view one as readonly
    viewItem = new CheckBoxItem(false);
    this.ItemTemplate = viewItem as ITemplate;

    // let the edit check box be editable
    editItem = new CheckBoxItem(true);
    this.EditItemTemplate = editItem as ITemplate;

Adding the Column to the DataGrid

The penultimate step is to add the column to the DataGrid itself. Because of the way we have designed the class this is simplicity itself as it can be used in place of a BoundColumn.

CheckBoxColumn checkCol = new CheckBoxColumn();
checkCol.HeaderText = "Boolean Field (Editable)";
checkCol.DataField = "Boolean";



Extracting the Updated State

The final step is extracting the data from the control itself when it comes to updating or inserting a row. Again we use a similar method as that normally employed however instead of a TextBox we use a CheckBox.

             = ((CheckBox)e.Item.Cells[4].Controls[0]).Checked;

AutoPostBack and receiving the CheckedChanged event

It was recently asked if it was possible to receive the CheckedChanged event from the CheckBoxes that were contained within the column. I have since updated the code to handle the scenario where you have a DataGrid with a CheckGridColumn and it is possible to update the field immediately.

Sample Image - checkgrid2.jpg

To add a column to our DataGrid that handles this sceanrio we do the following.

CheckBoxColumn checkCol2 = new CheckBoxColumn(true);
checkCol2.HeaderText = "Boolean Field (Always Editable)";
checkCol2.DataField = "Boolean";

// this is our handler for all of the CheckBoxes CheckedChanged events
checkCol2.CheckedChanged += new EventHandler(this.OnCheckChanged); 


Now because we need to handle the event to change our database entry we need to extract the relevent information from the DataGrid as well as extract the state of the CheckBox. The following sample shows how this could be done.
private void OnCheckChanged(object sender, EventArgs e)
	CheckBox box = (CheckBox) sender;
	DataGridItem container = (DataGridItem) box.NamingContainer;

	// get our values
                                = int.Parse(container.Cells[0].Text);
	sqlUpdateCommand1.Parameters["@Boolean"].Value = box.Checked;




The code has been documented using the /// documentation syntax. I prefer to use NDOC which can be found at Sourceforge for my Documentation generation engine. It also handles all those tags that Microsoft created and then forgot about.

Article History

29 July 2002 - Original Article Posted
03 Sept 2002 - Updated Article with Commented Source Code


Your feedback is important to me and I am always willing to make improvements. If you found this article useful don't forget to vote.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Shaun Wilde
Software Developer (Senior) MYOB
Australia Australia
All articles are supplied as-is, as a howto on a particular task that worked for me in the past. None of the articles are supposed to be out-of-the-box freeware controls and nor should they be treated as such. Caveat emptor.

Now living and working in Australia, trying to be involved in the local .NET and Agile communities when I can.

I spend a good chunk of my spare time building OpenCover and maintaining PartCover both of which are Code Coverage utilities for .NET.

You may also be interested in...

Comments and Discussions

GeneralRe: Event not firing Pin
dpilcher5-Jun-07 7:05
memberdpilcher5-Jun-07 7:05 
GeneralRe: Event not firing Pin
Shaun Wilde6-Jun-07 10:08
memberShaun Wilde6-Jun-07 10:08 
GeneralRe: Event not firing Pin
saleem33729-May-13 20:23
membersaleem33729-May-13 20:23 
GeneralAdding iTemplate function Pin
raja_raman8-May-07 21:44
memberraja_raman8-May-07 21:44 
GeneralRe: Adding iTemplate function Pin
raja_raman8-May-07 21:49
memberraja_raman8-May-07 21:49 
GeneralThanks a lot [modified] Pin
krausyd19-Apr-07 4:45
memberkrausyd19-Apr-07 4:45 
QuestionWhen i check the checkbox Pin
juliesamy25-Feb-07 18:28
memberjuliesamy25-Feb-07 18:28 
AnswerRe: When i check the checkbox Pin
Shaun Wilde25-Feb-07 22:40
memberShaun Wilde25-Feb-07 22:40 
Generalaccessing internal CheckBox. Pin
enerata21-Nov-06 10:34
memberenerata21-Nov-06 10:34 
GeneralRe: accessing internal CheckBox. Pin
Shaun Wilde25-Feb-07 22:37
memberShaun Wilde25-Feb-07 22:37 
Generaleditable datagrid column Pin
vidhu raj7-Sep-06 4:57
membervidhu raj7-Sep-06 4:57 
GeneralRe: editable datagrid column Pin
Shaun Wilde7-Sep-06 9:57
memberShaun Wilde7-Sep-06 9:57 
Generalboolean datatype problem Pin
Shayeb12-Jul-06 20:28
memberShayeb12-Jul-06 20:28 
GeneralRe: boolean datatype problem Pin
Shayeb12-Jul-06 20:39
memberShayeb12-Jul-06 20:39 
GeneralRe: boolean datatype problem Pin
Shaun Wilde12-Jul-06 23:55
memberShaun Wilde12-Jul-06 23:55 
Generalproblem with oncheckchange event Pin
quilla_b23-Jun-06 0:41
memberquilla_b23-Jun-06 0:41 
GeneralRe: problem with oncheckchange event Pin
Shaun Wilde23-Jun-06 3:42
memberShaun Wilde23-Jun-06 3:42 
GeneralRe: problem with oncheckchange event [modified] Pin
quilla_b25-Jun-06 19:11
memberquilla_b25-Jun-06 19:11 
GeneralRe: problem with oncheckchange event Pin
Shaun Wilde25-Jun-06 20:57
memberShaun Wilde25-Jun-06 20:57 
GeneralRe: problem with oncheckchange event [modified] Pin
quilla_b25-Jun-06 21:39
memberquilla_b25-Jun-06 21:39 
GeneralRe: problem with oncheckchange event Pin
Shaun Wilde26-Jun-06 0:34
memberShaun Wilde26-Jun-06 0:34 
GeneralRe: problem with oncheckchange event [modified] Pin
quilla_b26-Jun-06 1:16
memberquilla_b26-Jun-06 1:16 
QuestionWill you please read my post? Pin
nbaker18-May-06 8:31
membernbaker18-May-06 8:31 
AnswerRe: Will you please read my post? Pin
Shaun Wilde23-Jun-06 3:41
memberShaun Wilde23-Jun-06 3:41 
GeneralRegarding the checkBox ... Pin
ahjiefreak28-Apr-06 22:43
memberahjiefreak28-Apr-06 22:43 
GeneralRe: Regarding the checkBox ... Pin
Shaun Wilde29-Apr-06 0:11
memberShaun Wilde29-Apr-06 0:11 
GeneralUnable to cast object of type 'System.Data.Common.DbDataRecord' to type 'System.Data.DataRowView'. Pin
kanyakumari26-Apr-06 9:27
memberkanyakumari26-Apr-06 9:27 
GeneralRe: Unable to cast object of type 'System.Data.Common.DbDataRecord' to type 'System.Data.DataRowView'. Pin
kanyakumari26-Apr-06 11:28
memberkanyakumari26-Apr-06 11:28 
GeneralRe: Unable to cast object of type 'System.Data.Common.DbDataRecord' to type 'System.Data.DataRowView'. Pin
Shaun Wilde26-Apr-06 11:57
memberShaun Wilde26-Apr-06 11:57 
GeneralSorting Pin
mo_fya12-Apr-06 0:15
membermo_fya12-Apr-06 0:15 
GeneralRe: Sorting Pin
mo_fya19-Apr-06 0:41
membermo_fya19-Apr-06 0:41 
GeneralRe: Sorting Pin
Shaun Wilde19-Apr-06 10:06
memberShaun Wilde19-Apr-06 10:06 
GeneralITemplate throw System.NullReferenceException Pin
Rocko747-Apr-06 3:26
memberRocko747-Apr-06 3:26 
GeneralProblems whit other template columns Pin
Quick Frozen20-Mar-06 6:59
memberQuick Frozen20-Mar-06 6:59 
GeneralRe: Problems whit other template columns Pin
Shaun Wilde20-Mar-06 12:21
memberShaun Wilde20-Mar-06 12:21 
GeneralRe: Re: Problems whit other template columns Pin
Quick Frozen22-Mar-06 2:18
memberQuick Frozen22-Mar-06 2:18 
GeneralRe: Re: Problems whit other template columns Pin
Shaun Wilde22-Mar-06 6:26
memberShaun Wilde22-Mar-06 6:26 
AnswerRe: Re: Re: Problems whit other template columns Pin
Quick Frozen24-Mar-06 6:38
memberQuick Frozen24-Mar-06 6:38 
GeneralRe: Problems whit other template columns Pin
nilken14-Jul-06 22:26
membernilken14-Jul-06 22:26 
GeneralBoolean Field visibility Pin
doubleAbattery16-Mar-06 14:20
memberdoubleAbattery16-Mar-06 14:20 
GeneralRe: Boolean Field visibility Pin
Shaun Wilde16-Mar-06 22:28
memberShaun Wilde16-Mar-06 22:28 
GeneralProblems using .RenderControl() Pin
Saila On15-Feb-06 5:42
memberSaila On15-Feb-06 5:42 
GeneralRe: Problems using .RenderControl() Pin
Shaun Wilde15-Feb-06 12:38
memberShaun Wilde15-Feb-06 12:38 
GeneralRenderControl Pin
Saila On15-Feb-06 5:38
memberSaila On15-Feb-06 5:38 
Questionhow to manipulate web controls in datagrid? Pin
dotnetkoders6-Feb-06 18:31
memberdotnetkoders6-Feb-06 18:31 
AnswerRe: how to manipulate web controls in datagrid? Pin
Shaun Wilde8-Feb-06 19:32
memberShaun Wilde8-Feb-06 19:32 
GeneralPlease post entire sln Pin
Yoniraziel6-Dec-05 20:02
memberYoniraziel6-Dec-05 20:02 
GeneralRe: Please post entire sln Pin
Shaun Wilde8-Feb-06 19:33
memberShaun Wilde8-Feb-06 19:33 
GeneralProblem Pin
Aza1710-Nov-05 20:36
memberAza1710-Nov-05 20:36 
GeneralRe: Problem Pin
Shaun Wilde14-Nov-05 20:19
memberShaun Wilde14-Nov-05 20:19 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160426.1 | Last Updated 4 Sep 2002
Article Copyright 2002 by Shaun Wilde
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid