Click here to Skip to main content
11,638,351 members (76,842 online)
Click here to Skip to main content

How to create template columns dynamically in a grid view

, 17 Mar 2006 Ms-PL 395.1K 7K 80
Rate this:
Please Sign up or sign in to vote.
This article describes about how to create template columns dynamically in a grid view.
<!-- Article Starts - DO NOT ADD HTML/BODY START TAGS-->

Sample Image - DynamicColumnsWithTemplate.jpg

Introduction

This article describes about how to create template columns dynamically in a grid view.

Many times we have the requirement where we have to create columns dynamically. This article describes you about the dynamic loading of data using the DataTable as the datasource.

 

Let’s have a look at the code to understand better.

 

Create a gridview in the page,

  1. Drag and drop the GridView on to the page

Or

  1. Manually type GridView definition in the page.

 

<table border="0" cellpadding="0" cellspacing="0">

            <tr>

                <td>

                    <strong>Dynamic Grid with Template Column</strong></td>

            </tr>

            <tr>

                <td>

                    <asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False">

                    <Columns>

                    </Columns>

                    </asp:GridView>

                </td>

            </tr>

        </table>

 

With this we are done with creating a GridView in the page.

Let’s move on to the code-beside to understand the background history of the page.

Here I am describing about, how to create template columns.

 

//Iterate through the columns of the datatable to set the data bound field dynamically.

        foreach (DataColumn col in dt.Columns)

        {

            //Declare the bound field and allocate memory for the bound field.

            TemplateField bfield = new TemplateField();

 

            //Initalize the DataField value.

            bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);

 

            //Initialize the HeaderText field value.

            bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);

 

            //Add the newly created bound field to the GridView.

            GrdDynamic.Columns.Add(bfield);

        }

 

        //Initialize the DataSource

        GrdDynamic.DataSource = dt;

 

        //Bind the datatable with the GridView.

        GrdDynamic.DataBind();

   

Let’s start dissecting right from the top,

 

  1. Create a DataTable which will hold the table definition and data for the GridView. This table is used as a DataSource for the GridView.
    DataTable dt = new DataTable();
  2. Once the DataTable is created, let’s add 2 columns, ID & Name to the DataTable.
  3. The logic behind creating dynamic column starts by creating a TemplateField instance.
  4. Once the TemplateField is created, I am initializing the HeaderTemplate and ItemTemplate with the newly created GridViewTemplate.We will come back to the GridViewTemplate again.
  5. Once the creation of the dynamic columns is completed, I am assigning the DataSource of the GridView and call the DataBind method to load the GridView with data dynamically.

 

Let’s come back to the interesting part of the template columns i.e class GridViewTemplate.

//A customized class for displaying the Template Column

public class GridViewTemplate : ITemplate

{

    //A variable to hold the type of ListItemType.

    ListItemType _templateType;

 

    //A variable to hold the column name.

    string _columnName;

 

    //Constructor where we define the template type and column name.

    public GridViewTemplate(ListItemType type, string colname)

    {

        //Stores the template type.

        _templateType = type;

 

        //Stores the column name.

        _columnName = colname;

    }

 

    void ITemplate.InstantiateIn(System.Web.UI.Control container)

    {

        switch (_templateType)

        {

            case ListItemType.Header:

                //Creates a new label control and add it to the container.

                Label lbl = new Label();            //Allocates the new label object.

                lbl.Text = _columnName;             //Assigns the name of the column in the lable.

                container.Controls.Add(lbl);        //Adds the newly created label control to the container.

                break;

 

            case ListItemType.Item:

                //Creates a new text box control and add it to the container.

                TextBox tb1 = new TextBox();                            //Allocates the new text box object.

                tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.

                tb1.Columns = 4;                                        //Creates a column with size 4.

                container.Controls.Add(tb1);                            //Adds the newly created textbox to the container.

                break;

 

            case ListItemType.EditItem:

                //As, I am not using any EditItem, I didnot added any code here.

                break;

 

            case ListItemType.Footer:

                CheckBox chkColumn = new CheckBox();

                chkColumn.ID = "Chk" + _columnName;

                container.Controls.Add(chkColumn);

                break;

        }

    }

 

    /// <summary>

    /// This is the event, which will be raised when the binding happens.

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    void tb1_DataBinding(object sender, EventArgs e)

    {

        TextBox txtdata = (TextBox)sender;

        GridViewRow container = (GridViewRow)txtdata.NamingContainer;

        object dataValue = DataBinder.Eval(container.DataItem, _columnName);

        if (dataValue != DBNull.Value)

        {

            txtdata.Text = dataValue.ToString();

        }

    }

}

 

Any class that should be used as a template should be inherited from the ITemplate class.

ITemplate defines the behavior for populating a templated ASP.NET server control with child controls. The child controls represent the inline templates defined on the page.

 

One of the interesting method in the ITemplate class is InstantiateIn(Control Container),which defines the Control object that child controls and templates belong to. These child controls are in turn defined within an inline template.

 

In the InstanceIn method, based on the _templateType selected, I am creating the necessary controls.

 

That’s all your dynamic GridView is ready. I hope this information would be helpful.

 

There is another interesting scenario, I would like to bring forward. i.e let’s assume that we have added a button control to the page. Upon user clicking on the button control, the page gets post back. Once the page postback, and if we don’t create the template column again upon post back, the controls would disappear. This is one of the drawbacks of this approach.

 

Enjoy programming.

 

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Devakumar Sai Chinthala
Founder Articledean.com & conveygreetings.com
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
AnswerRe: Hey i have question regarding this gridview. Pin
AnirbanM 217-Dec-13 2:03
memberAnirbanM 217-Dec-13 2:03 
GeneralRe: Hey i have question regarding this gridview. Pin
Member 1118797728-Oct-14 14:05
memberMember 1118797728-Oct-14 14:05 
Questionadding html in gridview item template dynamically Pin
Anoop kumar singh9-Jun-12 12:13
memberAnoop kumar singh9-Jun-12 12:13 
GeneralMy vote of 5 Pin
sravani.v20-May-12 20:11
membersravani.v20-May-12 20:11 
QuestionAdding a Pager to the GridView Pin
cUbeindaclUb17-Apr-12 4:10
membercUbeindaclUb17-Apr-12 4:10 
QuestionGetting Problem Pin
kapilpandit18-Feb-12 0:47
memberkapilpandit18-Feb-12 0:47 
AnswerRe: Getting Problem Pin
Member 325336310-Mar-12 14:43
memberMember 325336310-Mar-12 14:43 
GeneralMy vote of 5 Pin
ElBilo11-Apr-11 15:32
memberElBilo11-Apr-11 15:32 
Generaladding the edititm template - issue Pin
ElBilo11-Apr-11 15:30
memberElBilo11-Apr-11 15:30 
GeneralRe: adding the edititm template - issue Pin
Member 997393230-Jul-13 5:23
memberMember 997393230-Jul-13 5:23 
QuestionGridview is being generated twice not sure why and what about editing Pin
Hazin1-Apr-11 7:54
memberHazin1-Apr-11 7:54 
AnswerRe: Gridview is being generated twice not sure why and what about editing Pin
Member 381661410-Apr-11 2:22
memberMember 381661410-Apr-11 2:22 
GeneralRe: Gridview is being generated twice not sure why and what about editing Pin
cUbeindaclUb17-Apr-12 3:24
membercUbeindaclUb17-Apr-12 3:24 
QuestionHow to read Values from Dynamically created Textbox.. Pin
selvashankard20-Dec-10 17:20
memberselvashankard20-Dec-10 17:20 
GeneralAdding text to TextBox Tooltip Pin
PeymaniuM26-Oct-10 19:57
memberPeymaniuM26-Oct-10 19:57 
GeneralCan't acess cell value Pin
Bijendra kumar das10-Sep-10 1:09
memberBijendra kumar das10-Sep-10 1:09 
QuestionHow to get the ID of created templatefields? Pin
K_Peters31-Aug-10 7:33
memberK_Peters31-Aug-10 7:33 
GeneralMight as well Log my issue, Unable to trap events in code behind Pin
Member 38952522-Apr-09 12:51
memberMember 38952522-Apr-09 12:51 
GeneralMy vote of 1 Pin
Shakeel Hussain19-Jan-09 0:22
memberShakeel Hussain19-Jan-09 0:22 
GeneralVariable text box sizes Pin
richiej5-Nov-07 6:41
memberrichiej5-Nov-07 6:41 
Questionhow to get the temporary created value at runtime in grid vie Pin
dsaikrishna6-Aug-07 21:42
memberdsaikrishna6-Aug-07 21:42 
QuestionHow to Update the Data. It is Posible. Pin
Ricardo Casquete19-Jun-07 5:42
memberRicardo Casquete19-Jun-07 5:42 
AnswerRe: How to Update the Data. It is Posible. Pin
bskvarma11-Jul-07 2:53
memberbskvarma11-Jul-07 2:53 
QuestionHow do I now setup a template? Pin
jonefer22-May-07 15:54
memberjonefer22-May-07 15:54 
QuestionGetting values from a dynamically generated column ? Pin
Binu from PITS7-May-07 19:16
memberBinu from PITS7-May-07 19:16 
AnswerRe: Getting values from a dynamically generated column ? Pin
manish_pandey1513-Sep-07 1:15
membermanish_pandey1513-Sep-07 1:15 
GeneralRe: Getting values from a dynamically generated column ? Pin
Member 46172057-Oct-08 13:27
memberMember 46172057-Oct-08 13:27 
QuestionSome issue after postback Pin
Hardy4-Dec-06 8:46
memberHardy4-Dec-06 8:46 
Generalhi Pin
neobeatle5-Nov-06 14:28
memberneobeatle5-Nov-06 14:28 
Questionhow to create programmatically InsertItemTemplate? Pin
herten25-Oct-06 6:04
memberherten25-Oct-06 6:04 
AnswerRe: how to create programmatically InsertItemTemplate? Pin
surajkikiran31-Aug-08 18:13
membersurajkikiran31-Aug-08 18:13 
QuestionHow can i catch the values of gridview which is dynamically created ? Pin
Vikas Pukale25-Sep-06 21:57
memberVikas Pukale25-Sep-06 21:57 
GeneralPostBack Pin
NuRoN12-Jul-06 3:47
memberNuRoN12-Jul-06 3:47 
AnswerRe: PostBack Pin
harrach6-Sep-06 1:56
memberharrach6-Sep-06 1:56 
GeneralRe: PostBack Pin
abhilashaVelhal8-Feb-12 1:04
memberabhilashaVelhal8-Feb-12 1:04 
GeneralRe: PostBack Pin
manish_pandey1513-Sep-07 2:00
membermanish_pandey1513-Sep-07 2:00 
GeneralRe: PostBack Pin
mahi988530-Jul-08 18:31
membermahi988530-Jul-08 18:31 
GeneralRe: PostBack Pin
shruk21-Oct-09 7:41
membershruk21-Oct-09 7:41 
Generalerror... Pin
sabrina.tremblay20-Jun-06 5:01
membersabrina.tremblay20-Jun-06 5:01 
Generalcomments incorrect Pin
nataliepea13-Jun-06 9:33
membernataliepea13-Jun-06 9:33 
GeneralUpdate cant be done with this method Pin
vijaygarg12-Jun-06 8:52
membervijaygarg12-Jun-06 8:52 
GeneralRe: Update cant be done with this method Pin
rajaryan_128031-Oct-09 3:26
memberrajaryan_128031-Oct-09 3:26 
QuestionEditable Columns Pin
Gene S22-May-06 14:21
memberGene S22-May-06 14:21 
AnswerRe: Editable Columns Pin
Member 38952523-Apr-09 5:29
memberMember 38952523-Apr-09 5:29 
GeneralDisplays Only the Last Column Pin
HemaRawat6-Apr-06 20:54
memberHemaRawat6-Apr-06 20:54 
QuestionCatch ImageButton event in TemplateField Pin
nounoors5-Apr-06 23:47
membernounoors5-Apr-06 23:47 
GeneralRe: Catch ImageButton event in TemplateField Pin
azjonesyyeah17-May-06 13:32
memberazjonesyyeah17-May-06 13:32 
GeneralRe: Catch ImageButton event in TemplateField Pin
kwathen12-Nov-06 1:15
memberkwathen12-Nov-06 1:15 
AnswerRe: Catch ImageButton event in TemplateField Pin
kwathen12-Nov-06 1:22
memberkwathen12-Nov-06 1:22 
GeneralRe: Catch ImageButton event in TemplateField Pin
nounoors12-Nov-06 21:57
membernounoors12-Nov-06 21:57 

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
Web03 | 2.8.150728.1 | Last Updated 17 Mar 2006
Article Copyright 2006 by Devakumar Sai Chinthala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid