Showing posts with label dynamic checkbox control for ultrawebgrid. Show all posts
Showing posts with label dynamic checkbox control for ultrawebgrid. Show all posts

Tuesday, September 22, 2009

Adding 'Template Column with checkbox control inside' dynamically to 'ultrawebgrid' (Infragistics)

I spent considerable amount of time to figure out how to add Template Column to Ultrawebgrid dynamically with checkbox control inside it... so I am providing code that helps you to achieve it...

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!Page.IsPostBack) //If you dn't add this then you get duplicate columns
AddTemplateColumn();
}

private void AddTemplateColumn()
{
TemplatedColumn tmp = new TemplatedColumn(true); //true to maintain viewstate
tmp.Width = Unit.Parse("60px");
tmp.Key = "ColumnName";
tmp.BaseColumnName ="ColumnName";
tmp.AllowRowFiltering = true;
tmp.GatherFilterData = Infragistics.WebUI.Shared.DefaultableBoolean.False;
tmp.DataType = "system.String";
tmp.Header.Caption = "anycaption";
tmp.Header.Title = "anycaption";
ChkboxTemplate temp = new ChkboxTemplate();
tmp.CellTemplate = temp;
WebGrid.DisplayLayout.Bands[0].Columns.Add(tmp);
}

private class ChkboxTemplate : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
CellItem cellitem = (CellItem)container;
CheckBox cbx = new CheckBox();
cbx.AutoPostBack = true;
cbx.EnableViewState = true;
cbx.Text = "TEXT";
cellitem.Controls.Add(cbx);
cellitem.Cell.AllowEditing = AllowEditing.No;
}
}

//you have to add this; if you want add some server side events for the control u added in template column
protected override void CreateChildControls()
{
base.CreateChildControls();

Infragistics.WebUI.UltraWebGrid.TemplatedColumn col = (TemplatedColumn)WebGrid.Columns.FromKey(columnName);
if (col != null)
{
for (int j = 0; j < WebGrid.Rows.Count; j++)
{
CheckBox cbx = ((CellItem)col.CellItems[j]).Controls[0] as CheckBox;
if (cbx != null)
{
cbx.ID = controlName;
cbx.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
}
}
}
}

//You must handle this event of the grid
void WebGrid_TemplatedColumnRestored(object sender, ColumnEventArgs e)
{
if (((TemplatedColumn)e.Column).CellTemplate == null)
{
((TemplatedColumn)e.Column).CellTemplate = new ChkboxTemplate();
}
}