5,693,062 members and growing! (19,018 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

Adding a CheckBox column to your DataGrid

By Shaun Wilde

A CheckBox column that is can be used and bound in a DataGrid
C#, Windows, .NET 1.0, .NET, Visual Studio, ASP.NET, Dev

Posted: 29 Jul 2002
Updated: 3 Sep 2002
Views: 660,722
Bookmarked: 169 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
123 votes for this Article.
Popularity: 9.28 Rating: 4.44 out of 5
5 votes, 4.3%
1
3 votes, 2.6%
2
1 vote, 0.9%
3
20 votes, 17.4%
4
86 votes, 74.8%
5

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.

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);
    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.

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.

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";

...

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.

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.

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

Shaun Wilde


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.

Been involved in programming from the early '80s. First on my Spectrum, then an Amstrad. Did lots of Fortran while at University before becoming involved in Forth, Prolog, Pascal, Occam, C and eventually C++. Eventually started programming on the Windows platform using Borland’s OWL framework, during my postgraduate years. When I started work in '94, I learnt MFC followed by COM and ATL and never looked back. Now working exclusively in .NET, working on WinForms, ASP.NET and the Compact Framework using C# and VB.NET. Using every bit of the .NET framework I can such as WebServices and writing my own controls for my .NET Portal, and for the Compact Framework. Still lots I don't know, but the end of the universe hasn't happened yet - I wonder if I'll have time?

I was a permanent employee for a number of companies until Dec 2000 before going independent after the DotCom I ws involved with went DotBomb. Now supplying consulting services to various institutions in London and surrounding regions i.e. UK Smile.

Now started using BizTalk and the latest .NET framework - yeha.
Occupation: Architect
Location: United Kingdom United Kingdom

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 322 (Total in Forum: 322) (Refresh)FirstPrevNext
Questionto restrict all the other check boxes when one check box is checkedmemberPHANINDRA.TSK21:22 30 Sep '08  
AnswerRe: to restrict all the other check boxes when one check box is checkedmemberShaun Wilde21:55 30 Sep '08  
GeneralRe: to restrict all the other check boxes when one check box is checkedmemberPHANINDRA.TSK23:51 30 Sep '08  
GeneralRe: to restrict all the other check boxes when one check box is checkedmemberShaun Wilde10:26 1 Oct '08  
GeneralKindly help +CheckboxmemberAjayTP5:27 25 Jul '08  
GeneralRe: Kindly help +CheckboxmemberShaun Wilde20:39 10 Aug '08  
GeneralMake Boolean Field (Editable) Invisiblemembershobsp4:31 18 Jun '08  
GeneralRe: Make Boolean Field (Editable) InvisiblememberShaun Wilde20:37 10 Aug '08  
Generalnot workingmemberravicool21:52 8 May '08  
GeneralRe: not workingmember Shaun Wilde 4:48 9 May '08  
GeneralCheckbox event not firingmemberambahdagreat11:12 4 Oct '07  
GeneralRe: Checkbox event not firingmemberShaun Wilde22:33 4 Oct '07  
GeneralRe: Checkbox event not firingmemberambahdagreat6:12 5 Oct '07  
AnswerRe: Checkbox event not firingmember0bit10:32 5 Oct '07  
GeneralRe: Checkbox event not firingmemberambahdagreat11:38 5 Oct '07  
GeneralRe: Checkbox event not firingmemberShaun Wilde10:55 6 Oct '07  
QuestionEvent not firingmemberdpilcher11:45 4 Jun '07  
AnswerRe: Event not firingmemberShaun Wilde0:05 5 Jun '07  
GeneralRe: Event not firingmemberdpilcher6:28 5 Jun '07  
GeneralRe: Event not firingmemberdpilcher6:36 5 Jun '07  
GeneralRe: Event not firingmemberdpilcher6:57 5 Jun '07  
GeneralRe: Event not firingmemberdpilcher8:05 5 Jun '07  
GeneralRe: Event not firingmemberShaun Wilde11:08 6 Jun '07  
GeneralAdding iTemplate functionmemberraja_raman22:44 8 May '07  
GeneralRe: Adding iTemplate functionmemberraja_raman22:49 8 May '07