Click here to Skip to main content
Click here to Skip to main content

Dynamically Adding Template Columns to a GridView

, 8 Jan 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
How to add template columns dynamically to a GridView.


Many a times we wonder how to add a template column dynamically. This might be the case when the number of columns, column types etc., cannot be decided during design time. For example, if the data source of a GridView control will be retrieved from a Business Layer, when designing the GridView user interface, the developer can not determine the number of columns and other things related to column description. In such a case, the GridView will be configured to generate columns automatically at runtime. Adding template columns at runtime was not possible in earlier versions of .NET, i.e., 1.0. With the new version of .NET 2.0 onwards, there is a facility to add template columns at runtime dynamically.

For the above purpose, I have created a class DynamicTemplate inheriting the ITemplate interface.

public class DynamicTemplate : System.Web.UI.ITemplate

Now the very first step is to implement the constructor for the class:

public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
    templateType = type;

Here I have passed ListItemType as a parameter to the constructor, which will define the type of the current template. I.e., the template can be a Header, Item, AlternatingItem, or Footer.

Next, for defining the type of the control template column will be displaying, I have added the following method:

public void AddControl(WebControl wbControl, 
            String BindPropertyName, String BindExpression)
    htControls.Add(htControls.Count, wbControl);
    htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
    htBindExpression.Add(htBindExpression.Count, BindExpression);

Here we need to pass three parameters: wbcontrol is the reference to any web control which we want our template column to display, BindPropertyName is the property name of the control to be bound, e.g., the Text property for a TextBox or Label control, and BindExpression is the field name or any valid Bind expression to be evaluated and assigned to the BindProperty.

Now for providing template column functionality, we need to implement the 'InstantiateIn' method. This method will be called for every row of the GridView before binding occurs.

public void InstantiateIn(System.Web.UI.Control container)
    PlaceHolder ph = new PlaceHolder();
    for (int i = 0; i < htControls.Count; i++)
        //clone control 
        Control cntrl = CloneControl((Control)htControls[i]);
        switch (templateType)
            case ListItemType.Header:
            case ListItemType.Item:
            case ListItemType.AlternatingItem:
                ph.DataBinding += new EventHandler(Item_DataBinding);
            case ListItemType.Footer:
    ph.DataBinding += new EventHandler(Item_DataBinding);

Here, we first clone the web control so that a new copy can be created, and then we add this new copy to the desired placeholder.

Next, we want to implement this class for adding the template column dynamically:

TemplateField t = new TemplateField();
DynamicTemplate mt = new DynamicTemplate(ListItemType.Item);
TextBox t1 = new TextBox();
t1.ID = "txt";
t1.Visible = true;
t1.Text = "1";
mt.AddControl(t1, "Text", "Sno");

Here we are creating a template column which will display a TextBox. And the Text property of this TextBox will be bound with the Sno data field of the configured data source.

A complete implementation of the above class is attached with this article, which is quite self-explanatory and simple.


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


About the Author

Vikramaditya S Shekhawat
India India
Originally from Jaipur(Rajasthan).
Working in Norway for a Software company.Holding diploma from CDAC and MCSD.NET (C#).

Comments and Discussions

GeneralComment Pinmemberloweryk5-Dec-14 6:42 
Questioni want to create grid view col like days of months like aug 1 to 31 and col name is also 1to 31 Pinmemberganew24-Aug-14 21:12 
QuestionGirdView next page action the dynamic template column values not visible PinmemberMahesh200927-Aug-13 5:27 
General[My vote of 2] Link button header - Commnad event not fire........... PinmemberSanjay g. Patel31-May-11 3:02 
GeneralHaving Period (or dot) in column name Pinmemberfarhan1406-Apr-11 0:56 
GeneralBinding problem with radio button list Pinmemberimrajanc18-Jan-10 22:09 
GeneralPage_Init PinmemberMember 212971517-Nov-09 6:33 
GeneralDynamically adding Template columns to a GridView after closing PopUP window Pinmemberkshafer30-Oct-09 11:39 
GeneralTexbox appearance problem PinmemberMember 591532825-Jul-09 10:21 
GeneralThanks Pinmemberarsalan_qamar27-May-09 7:09 
GeneralMy vote of 1 [modified] PinmemberWilko Gesink20-Feb-09 17:09 
GeneralRe: My vote of 1 Pinmemberarsalan_qamar27-May-09 7:06 
GeneralRe: My vote of 1 PinmemberVikramaditya S Shekhawat28-Jul-09 0:27 
QuestionDynamically Adding multiple columns PinmemberMSwati27-Jan-09 21:08 
QuestionDynamically Adding columns to existing datasource PinmemberMSwati18-Jan-09 21:28 
AnswerRe: Dynamically Adding columns to existing datasource PinmemberVikramaditya S Shekhawat20-Jan-09 5:16 
GeneralRe: Dynamically Adding columns to existing datasource PinmemberMSwati20-Jan-09 20:00 
Generalgenerate colums of the gridview from the listbox and make a header template dynamically Pinmemberpratap2k417-Jan-09 3:41 
GeneralUnable to retrieve value from Text Box that was added dynamically containing Blank Text Pinmemberanshubansal200021-Nov-08 9:05 
Generalrowcommand event is not fire PinmemberTripathi Swati24-Sep-08 21:54 
GeneralRe: rowcommand event is not fire PinmemberSanjay g. Patel30-May-11 23:19 
GeneralDynamically Adding Template columns Pinmembersandla31-Jul-08 22:09 
Generalgrid view Pinmemberclaradaisy14-Jul-08 20:29 
Questionadding click events?? Pinmemberprochaska23-May-08 10:50 
NewsError assigning integer Column to textbox PinmemberMember 7657327-May-08 16:52 
QuestionHi! I have added textboxes in gridview dynamically PinmemberAbhijit Aitwade22-Feb-08 0:42 
AnswerRe: Hi! I have added textboxes in gridview dynamically PinmemberAshish19786-Sep-08 21:31 
Generalone textbox per column PinmemberCraig Graham16-Oct-07 7:26 
QuestionPostBack ? Pinmemberblublu7810-Oct-07 5:24 
AnswerRe: PostBack ? PinmemberCraig Graham16-Oct-07 7:28 
GeneralRe: PostBack ? Pinmemberarsalan_qamar27-May-09 7:07 
Generaltemplate fields disappeared after postback Pinmemberchronossu2-Oct-07 0:18 
GeneralHelp with the addControl Method PinmemberJohn Gilmore25-Sep-07 13:27 
GeneralRe: Help with the addControl Method PinmemberJohn Gilmore26-Sep-07 4:20 
GeneralProb ... please help Pinmemberdheeraj dhawan12-Aug-07 22:08 
GeneralDatabinding is Giving Problem PinmemberBaldev Rawat28-Jul-07 20:31 
GeneralRe: Databinding is Giving Problem PinmemberJohn Gilmore26-Sep-07 4:19 
GeneralError with Imagebutton PinmemberJoshua Lunsford25-Jul-07 7:09 
GeneralRe: Error with Imagebutton PinmemberJoshua Lunsford25-Jul-07 7:34 
GeneralRe: Error with Imagebutton PinmemberJohn Gilmore26-Sep-07 7:23 
Generaleasy way to add cols dynamically Pinmembermuhammadali11-Feb-09 5:39 
GeneralNot able to add Header to the Row Pinmembersrvking14-Jun-07 2:55 
GeneralRe: Not able to add Header to the Row Pinmembermanmohanshah18-Sep-08 0:46 
Generallayout formating is being removed Pinmemberkenken071022-May-07 20:54 
AnswerRe: layout formating is being removed Pinmembersdwilly2212-Jun-08 6:58 
GeneralThanx PinmemberPallavi Bhoite21-May-07 23:05 
Questionhow to add dropdown? PinmemberUmer Khan13-Apr-07 3:17 
GeneralCan't access the controls in the column PinmemberBalaji Iyengar9-Apr-07 1:02 
GeneralRe: Can't access the controls in the column Pinmembermanish_pandey1513-Sep-07 2:15 
QuestionHow can I use GridView instead of label Control PinmemberJawad Munir15-Mar-07 20:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.1 | Last Updated 8 Jan 2007
Article Copyright 2007 by Vikramaditya S Shekhawat
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid