DataGrid ITemplate Columns: Programatically adding columns and wiring events for controls January 10, 2006Posted by codinglifestyle in ASP.NET, C#.
Tags: ASP.NET, datagrid, ITemplateField
One of the great features of the DataGrid is that ability to add ITemplate derived columns which can host any control you like. For example a column displaying a checkbox or radiobutton can leverage DataGrid’s select feature. It is trivial enough to add a ITemplate column and wire up events in the web designer, but a different story to do so programatically.
public class RadioButtonColumn : ITemplate
private RadioButton m_rb;
public void InstantiateIn(Control container)
m_rb = new RadioButton();
m_rb.AutoPostBack = true;
m_rb.CheckedChanged +=new EventHandler(m_rb_CheckedChanged);
private void m_rb_CheckedChanged(object sender, EventArgs e)
RadioButton rb = (RadioButton) sender;
DataGridItem container = (DataGridItem) rb.NamingContainer;
DataGrid dg = (DataGrid)container.Parent.Parent;
When dynamically adding a ITemplate column to the datagrid control, ITemplate.InstantiateIn will be called when your datagrid is databinding. So make sure to set up the grid’s columns before you DataBind(). The RadioButtonColumn class will simply display a radio button for each row when added to DataGrid.Columns (DataGrid.AutoGenerateColumns should = false). However you will notice the event is never fired.
During Page postback the DataGrid.DataBind method will not be called in time to wire up the event because the datagrid columns will be re-created from the ViewState. To make the ITemplate column event’s work place your column into the datagrid before the LoadViewState method is called otherwise ITemplate.InstantiateIn will not be called. In the ASP.NET lifecycle, LoadViewState method is called before the Load event
and after the Init event, so placing your code into the Init event will wire the event in time to be called.