Click here to Skip to main content
Licence Ms-PL
First Posted 17 Mar 2006
Views 257,085
Bookmarked 67 times

How to create template columns dynamically in a grid view

By | 17 Mar 2006 | Article
This article describes about how to create template columns dynamically in a grid view.

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)

About the Author

Devakumar Sai Chinthala

Founder
Articledean.com & conveygreetings.com
United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembersravani.v20:11 20 May '12  
QuestionAdding a Pager to the GridView PinmembercUbeindaclUb4:10 17 Apr '12  
QuestionGetting Problem Pinmemberkapilpandit0:47 18 Feb '12  
AnswerRe: Getting Problem PinmemberMember 325336314:43 10 Mar '12  
GeneralMy vote of 5 PinmemberElBilo15:32 11 Apr '11  
Generaladding the edititm template - issue PinmemberElBilo15:30 11 Apr '11  
QuestionGridview is being generated twice not sure why and what about editing PinmemberHazin7:54 1 Apr '11  
AnswerRe: Gridview is being generated twice not sure why and what about editing PinmemberMember 38166142:22 10 Apr '11  
GeneralRe: Gridview is being generated twice not sure why and what about editing PinmembercUbeindaclUb3:24 17 Apr '12  
QuestionHow to read Values from Dynamically created Textbox.. Pinmemberselvashankard17:20 20 Dec '10  
GeneralAdding text to TextBox Tooltip PinmemberPeymaniuM19:57 26 Oct '10  
GeneralCan't acess cell value PinmemberBijendra kumar das1:09 10 Sep '10  
QuestionHow to get the ID of created templatefields? PinmemberK_Peters7:33 31 Aug '10  
GeneralMight as well Log my issue, Unable to trap events in code behind PinmemberMember 389525212:51 2 Apr '09  
GeneralMy vote of 1 PinmemberShakeel Hussain0:22 19 Jan '09  
GeneralVariable text box sizes Pinmemberrichiej6:41 5 Nov '07  
Questionhow to get the temporary created value at runtime in grid vie Pinmemberdsaikrishna21:42 6 Aug '07  
QuestionHow to Update the Data. It is Posible. PinmemberRicardo Casquete5:42 19 Jun '07  
AnswerRe: How to Update the Data. It is Posible. Pinmemberbskvarma2:53 11 Jul '07  
QuestionHow do I now setup a template? Pinmemberjonefer15:54 22 May '07  
QuestionGetting values from a dynamically generated column ? PinmemberBinu from PITS19:16 7 May '07  
AnswerRe: Getting values from a dynamically generated column ? Pinmembermanish_pandey151:15 13 Sep '07  
GeneralRe: Getting values from a dynamically generated column ? PinmemberMember 461720513:27 7 Oct '08  
QuestionSome issue after postback PinmemberHardy8:46 4 Dec '06  
I modified your code a little bit to add pager inside, my change is
 
Line 45: loop until 100 to make pager visible.
 
Added following code:
protected void GrdDynamic_PageIndexChanging(object sender, GridViewPageEventArgs e) {
GrdDynamic.PageIndex = e.NewPageIndex;
loadDynamicGridWithTemplateColumn();
}
 
Changes definition of GridView to include event handler of page index changing.
<asp:GridView ID="GrdDynamic" runat="server" AllowPaging="True" AutoGenerateColumns="False" OnPageIndexChanging="GrdDynamic_PageIndexChanging">
 
After several postback by clicking page number, you will see 4 columns visible on screen!!
 

 

Complete Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">

Dynamic Grid with Template Column
<asp:GridView ID="GrdDynamic" runat="server" AllowPaging="True" AutoGenerateColumns="False" OnPageIndexChanging="GrdDynamic_PageIndexChanging">




<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
 

Complete Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
 
public partial class _Default : System.Web.UI.Page
{
#region constants
const string NAME = "NAME";
const string ID = "ID";
#endregion
 
protected void Page_Load(object sender, EventArgs e)
{
loadDynamicGridWithTemplateColumn();
}
 
private void loadDynamicGridWithTemplateColumn()
{
#region Code for preparing the DataTable
 
//Create an instance of DataTable
DataTable dt = new DataTable();
 
//Create an ID column for adding to the Datatable
DataColumn dcol = new DataColumn(ID, typeof(System.Int32));
dcol.AutoIncrement = true;
dt.Columns.Add(dcol);
 
//Create an ID column for adding to the Datatable
dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
 
//Now add data for dynamic columns
//As the first column is auto-increment, we do not have to add any thing.
//Let's add some data to the second column.
for (int nIndex = 0; nIndex < 100; nIndex++)
{
//Create a new row
DataRow drow = dt.NewRow();
 
//Initialize the row data.
drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));
 
//Add the row to the datatable.
dt.Rows.Add(drow);
}
#endregion
 
//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();
}
protected void GrdDynamic_PageIndexChanging(object sender, GridViewPageEventArgs e) {
GrdDynamic.PageIndex = e.NewPageIndex;
loadDynamicGridWithTemplateColumn();
}
}
 
WWW: http://www.imagestation.com/members/hardywang
ICQ: 3359839
yours Hardy

Generalhi Pinmemberneobeatle14:28 5 Nov '06  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 17 Mar 2006
Article Copyright 2006 by Devakumar Sai Chinthala
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid