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

Adding a CheckBox column to your DataGrid

Rate me:
Please Sign up or sign in to vote.
4.79/5 (126 votes)
3 Sep 2002CPOL3 min read 1.7M   13.1K   205   327
A CheckBox column that is can be used and bound in a DataGrid

Sample Image - checkgrid.jpg

Introduction

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.

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

C#
void ITemplate.InstantiateIn(Control container)
{
    CheckBox box = new CheckBox();
    box.DataBinding += new EventHandler(this.BindData);
    container.Controls.Add(box);
}

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.

C#
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)
    container.DataItem).DataView.Table.Columns[dataField].DataType;
    if (data.Length>0)
    {
        switch (type.ToString())
        {
        case "System.Boolean":
            if ( data == "True")
            {
                box.Checked = true;
            }
            break;
        default:
            break;
        }
    }
}

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.

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

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

...

DataGrid1.Columns.Add(checkCol);

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.

C#
sqlUpdateCommand1.Parameters["@Boolean"].Value
             = ((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.

C#
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); 

...

DataGrid2.Columns.Add(checkCol2);
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.
C#
private void OnCheckChanged(object sender, EventArgs e)
{
	CheckBox box = (CheckBox) sender;
	DataGridItem container = (DataGridItem) box.NamingContainer;

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

...

}

Documentation

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

Feedback

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.

</body></html>

License

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


Written By
Employed (other) Purplebricks
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.

Comments and Discussions

 
GeneralRe: c# beginner Pin
Shaun Wilde13-Mar-04 1:25
Shaun Wilde13-Mar-04 1:25 
GeneralRe: c# beginner Pin
clare12314-Mar-04 23:17
clare12314-Mar-04 23:17 
GeneralRe: c# beginner Pin
Shaun Wilde15-Mar-04 9:54
Shaun Wilde15-Mar-04 9:54 
GeneralRe: c# beginner Pin
clare12315-Mar-04 21:42
clare12315-Mar-04 21:42 
GeneralRe: c# beginner Pin
Shaun Wilde16-Mar-04 3:35
Shaun Wilde16-Mar-04 3:35 
GeneralRe: c# beginner Pin
cartmann4-Jun-04 4:52
cartmann4-Jun-04 4:52 
GeneralRe: c# beginner Pin
cartmann4-Jun-04 4:59
cartmann4-Jun-04 4:59 
GeneralRe: c# beginner Pin
Shaun Wilde10-Jun-04 0:08
Shaun Wilde10-Jun-04 0:08 
GeneralRe: c# beginner Pin
cartmann13-Jun-04 20:22
cartmann13-Jun-04 20:22 
GeneralCheckBoxColumn for VB.NET Pin
twillhauck9-Mar-04 21:04
twillhauck9-Mar-04 21:04 
GeneralRe: CheckBoxColumn for VB.NET Pin
Shaun Wilde12-Mar-04 8:40
Shaun Wilde12-Mar-04 8:40 
GeneralCheck Box Column not seen Pin
Ananthanatarajan6-Mar-04 7:35
Ananthanatarajan6-Mar-04 7:35 
GeneralRe: Check Box Column not seen Pin
Shaun Wilde6-Mar-04 9:34
Shaun Wilde6-Mar-04 9:34 
GeneralRe: Check Box Column not seen Pin
Ananthanatarajan8-Mar-04 0:43
Ananthanatarajan8-Mar-04 0:43 
GeneralRe: Check Box Column not seen Pin
Shaun Wilde8-Mar-04 8:46
Shaun Wilde8-Mar-04 8:46 
GeneralCannot See the Checkbox Pin
CSharpdotnet24-Feb-04 6:56
CSharpdotnet24-Feb-04 6:56 
GeneralRe: Cannot See the Checkbox Pin
Shaun Wilde24-Feb-04 8:51
Shaun Wilde24-Feb-04 8:51 
GeneralRe: Cannot See the Checkbox Pin
Shayeb12-Jul-06 23:50
Shayeb12-Jul-06 23:50 
Generaldifferent control for the same column Pin
Keynan_d21-Feb-04 21:27
Keynan_d21-Feb-04 21:27 
GeneralRe: different control for the same column Pin
Shaun Wilde22-Feb-04 2:57
Shaun Wilde22-Feb-04 2:57 
QuestionHow to use this in a templated datagrid column created dynamically? Pin
valmir196918-Feb-04 3:11
professionalvalmir196918-Feb-04 3:11 
AnswerRe: How to use this in a templated datagrid column created dynamically? Pin
Shaun Wilde22-Feb-04 2:49
Shaun Wilde22-Feb-04 2:49 
GeneralPost Back loses all check boxes. Pin
stevensclint21-Nov-03 7:09
stevensclint21-Nov-03 7:09 
GeneralRe: Post Back loses all check boxes. Pin
Shaun Wilde21-Nov-03 8:04
Shaun Wilde21-Nov-03 8:04 
GeneralRe: Post Back loses all check boxes. Pin
Shaun Wilde21-Nov-03 8:04
Shaun Wilde21-Nov-03 8:04 

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.