Click here to Skip to main content
15,438,393 members
Articles / Web Development / ASP.NET
Posted 8 Jan 2007


40 bookmarked

Dynamically Adding Template Columns to a GridView

Rate me:
Please Sign up or sign in to vote.
3.32/5 (18 votes)
8 Jan 2007CPOL2 min read
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)

Written By
Norway Norway
Growing up with the world wide web, witnessing many bubbles and the rise of information technology to becoming an indispensable part of human existence, I was intrigued and astonished by the drastic changes it brought to the way we lived then. I was drawn into this whirlpool of internet and technology as an enthusiast only to come out as a qualified software professional. Worked extensively on technologies, starting with Visual Basic, ASP, Oracle and MS SQL to WCF, .NET Core , Azure service fabric and Kubernetes. Architected applications for on-premises to hybrid clouds to cloud native environments.
Fortunately, I like what I do and work has been fulfilling.
It has been 20+ years of working for various organisations in several roles both technical and managerial but not a
dull day.

Comments and Discussions

GeneralComment Pin
loweryk5-Dec-14 5:42
Memberloweryk5-Dec-14 5:42 
Questioni want to create grid view col like days of months like aug 1 to 31 and col name is also 1to 31 Pin
ganew24-Aug-14 20:12
Memberganew24-Aug-14 20:12 
QuestionGirdView next page action the dynamic template column values not visible Pin
Mahesh200927-Aug-13 4:27
MemberMahesh200927-Aug-13 4:27 
General[My vote of 2] Link button header - Commnad event not fire........... Pin
Sanjay g. Patel31-May-11 2:02
MemberSanjay g. Patel31-May-11 2:02 
GeneralHaving Period (or dot) in column name Pin
farhan1405-Apr-11 23:56
Memberfarhan1405-Apr-11 23:56 
GeneralBinding problem with radio button list Pin
rajan.chellappan18-Jan-10 21:09
Memberrajan.chellappan18-Jan-10 21:09 
GeneralPage_Init Pin
Member 212971517-Nov-09 5:33
MemberMember 212971517-Nov-09 5:33 
GeneralDynamically adding Template columns to a GridView after closing PopUP window Pin
kshafer30-Oct-09 10:39
Memberkshafer30-Oct-09 10:39 
GeneralTexbox appearance problem Pin
Member 591532825-Jul-09 9:21
MemberMember 591532825-Jul-09 9:21 
GeneralThanks Pin
arsalan_qamar27-May-09 6:09
Memberarsalan_qamar27-May-09 6:09 
GeneralMy vote of 1 [modified] Pin
Wilko Gesink20-Feb-09 16:09
MemberWilko Gesink20-Feb-09 16:09 
GeneralRe: My vote of 1 Pin
arsalan_qamar27-May-09 6:06
Memberarsalan_qamar27-May-09 6:06 
GeneralRe: My vote of 1 Pin
Vikramaditya S Shekhawat27-Jul-09 23:27
MemberVikramaditya S Shekhawat27-Jul-09 23:27 
QuestionDynamically Adding multiple columns Pin
MSwati27-Jan-09 20:08
MemberMSwati27-Jan-09 20:08 
AnswerRe: Dynamically Adding multiple columns Pin
phoohtoo21-Aug-15 1:20
Memberphoohtoo21-Aug-15 1:20 
QuestionDynamically Adding columns to existing datasource Pin
MSwati18-Jan-09 20:28
MemberMSwati18-Jan-09 20:28 
AnswerRe: Dynamically Adding columns to existing datasource Pin
Vikramaditya S Shekhawat20-Jan-09 4:16
MemberVikramaditya S Shekhawat20-Jan-09 4:16 
GeneralRe: Dynamically Adding columns to existing datasource Pin
MSwati20-Jan-09 19:00
MemberMSwati20-Jan-09 19:00 
Generalgenerate colums of the gridview from the listbox and make a header template dynamically Pin
pratap2k417-Jan-09 2:41
Memberpratap2k417-Jan-09 2:41 
GeneralUnable to retrieve value from Text Box that was added dynamically containing Blank Text Pin
anshubansal200021-Nov-08 8:05
Memberanshubansal200021-Nov-08 8:05 
Generalrowcommand event is not fire Pin
Tripathi Swati24-Sep-08 20:54
MemberTripathi Swati24-Sep-08 20:54 
GeneralRe: rowcommand event is not fire Pin
Sanjay g. Patel30-May-11 22:19
MemberSanjay g. Patel30-May-11 22:19 
GeneralHi Vikramaditya Pin
dhassen13-Aug-08 0:03
Memberdhassen13-Aug-08 0:03 
GeneralDynamically Adding Template columns Pin
sandla31-Jul-08 21:09
Membersandla31-Jul-08 21:09 
Generalgrid view Pin
claradaisy14-Jul-08 19:29
Memberclaradaisy14-Jul-08 19:29 

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

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