Saturday, November 3, 2012

Add Normal Column and Template Column Dynamically in Asp.net GridView

in most of case we build GridView statically or let asp.net do it it self but what if we want to add Columns to GridView Dynamically.like you may want to add TemplateField  with Several controls within it with code too.

Fist we will see how to add Normal column to GridView at runtime.
BoundField FirstName = new BoundField();
FirstName.DataField = "Some Database Field";
FirstName.HeaderText = "First Name";

GridView1.Columns.Add(FirstName);
Next , How to add Field With Custom template.to add Column with custom template you need to First Define Template using code for that you need to implement ITemplate interface. here is sample code about doing it .
/* Create Template Field by Implementing ITemplate */
public class MyCustomTemplate:ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        CheckBox cb = new CheckBox();
        cb.ID = "testCheckBox";
        cb.Text = "Test";
        container.Controls.Add(cb);
    }
}
/* Adding Field With Template */
TemplateField tf = new TemplateField();
tf.HeaderText = "Custom Template Field Column";
tf.ItemTemplate = new MyCustomTemplate();

GridView1.Columns.Add(tf);
above example We Created Template of Item within the column with one check box by Implementing ITemplate Interface which we can set as Item Template while we Add TemplateField in GridView.

No comments: