Click here to Skip to main content
15,886,110 members
Articles / Web Development / ASP.NET

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 233.8K   2.2K   41   55
How to add template columns dynamically to a GridView.

Introduction

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.

C#
public class DynamicTemplate : System.Web.UI.ITemplate

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

C#
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:

C#
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.

C#
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:
                break;
            case ListItemType.Item:
                ph.Controls.Add(cntrl);
                break;
            case ListItemType.AlternatingItem:
                ph.Controls.Add(cntrl);
                ph.DataBinding += new EventHandler(Item_DataBinding);
                break;
            case ListItemType.Footer:
                break;
        }
    }
    ph.DataBinding += new EventHandler(Item_DataBinding);
    container.Controls.Add(ph);
}

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:

C#
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.

License

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


Written By
Architect
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

 
GeneralRe: Not able to add Header to the Row Pin
manmohanshah17-Sep-08 23:46
manmohanshah17-Sep-08 23:46 
Generallayout formating is being removed Pin
kenken071022-May-07 19:54
kenken071022-May-07 19:54 
AnswerRe: layout formating is being removed Pin
sdwilly2212-Jun-08 5:58
sdwilly2212-Jun-08 5:58 
GeneralThanx Pin
Pallavi Bhoite21-May-07 22:05
Pallavi Bhoite21-May-07 22:05 
Questionhow to add dropdown? Pin
Umer Khan13-Apr-07 2:17
Umer Khan13-Apr-07 2:17 
GeneralCan't access the controls in the column Pin
Balaji Iyengar9-Apr-07 0:02
Balaji Iyengar9-Apr-07 0:02 
GeneralRe: Can't access the controls in the column Pin
manish_pandey1513-Sep-07 1:15
manish_pandey1513-Sep-07 1:15 
QuestionHow can I use GridView instead of label Control Pin
Jawad Munir15-Mar-07 19:58
Jawad Munir15-Mar-07 19:58 
Dear Vikramaditya S Shekhawat
First of all excellent work.
Well my requirements are different. I want to add GridView control in all the template columns and rest of the labels will be added and bound as well in that inner GridView.
I followed the steps and for each column/N I added template columns in the Main GridView and in Each column I added another GridView that contains N template column each containing a label control that are binded with my DataTable (Consider Table 0 of dataset).
Everything goes fine. But there i am required to bind the inner GridView as well. I I pass empty strings to the Function
AddControl
as the inner grid is not bound to any field but contains columns that are already bounded in the inner loop where I added those lables/Columns.

Kindly let me know or suggest.

Regards,

Jawad Munir

GeneralCloneControl() is missing.... Pin
connectpalm28-Feb-07 3:23
connectpalm28-Feb-07 3:23 
GeneralRe: CloneControl() is missing.... Pin
Vikramaditya S Shekhawat14-Mar-07 21:32
Vikramaditya S Shekhawat14-Mar-07 21:32 
GeneralNice one Pin
Sendilkumar.M8-Jan-07 18:55
Sendilkumar.M8-Jan-07 18:55 

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.