Runtime Dynamically Creating Template Column in GridView and Bind Data Using Asp.Net C# VB.Net

In some complex scenarios developers need to create runtime GridView dynamically. So obviously developers need to create dynamic Bound columns as well as Template columns for dynamic Gridviews. Here in this article I will explain how one can develop or implement run time dynamically create bound column and template column of a GridView control and also how to bind data into the dynamically created GridView Bound column & Template Column. For simplicity here i use a datatable but you can bind data from database as well. Here I will also explain how developers can create dynamic event handler for dynamically created Template column Button to accomplish the requirement.

Objective/Outcome:
Runtime Dynamically Creating Template Column in GridView and Bind Data Using Asp.Net Csharp VB.Net

Now add a PlacHolder in your Page to place the Dynamically Created GridView:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Creating Bound column is easier than Template column because if you want to add dynamic Template column in your GridView then you must implement ITemplate interface. When you instantiate the implemented object then it will automatically call the “InstantiateIn” method. To implement my example first add a class in your project and named it “TemplateHandler”. Then copy the below code sample:

C# Code:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class TemplateHandler : ITemplate
{
    void ITemplate.InstantiateIn(Control container)
    {
        Button cmd = new Button();
        cmd.ID = "cmd";
        cmd.Text = "Click Me";
        cmd.Click += new EventHandler(Dynamic_Method);
        container.Controls.Add(cmd);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        ((Button)sender).Text = "Clicked Record ID IS: " + ((Button)sender).CommandName;
    }
}

VB.Net Code:

Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class TemplateHandler
    Implements ITemplate
    Private Sub ITemplate_InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
        Dim cmd As New Button()
        cmd.ID = "cmd"
        cmd.Text = "Click Me"
        AddHandler cmd.Click, AddressOf Me.Dynamic_Method
        container.Controls.Add(cmd)
    End Sub

    Protected Sub Dynamic_Method(sender As Object, e As EventArgs)
        DirectCast(sender, Button).Text = "Clicked Record ID IS: " + DirectCast(sender, Button).CommandName
    End Sub
End Class

Now Create Dynamic Template Column & GridView in Run time:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
            DataTable dt = new DataTable();

            dt.Columns.Add("ID", System.Type.GetType("System.Int64"));    
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            dt.Columns.Add("Age", typeof(System.Int32));

            DataRow oItem = dt.NewRow();
            oItem[0] = "1000";
            oItem[1] = "Shawpnendu";
            oItem[2] = "Bikash";
            oItem[3] = 32;
            dt.Rows.Add(oItem);

            oItem = dt.NewRow();
            oItem[0] = "2000";
            oItem[1] = "Bimalendu";
            oItem[2] = "Bikash";
            oItem[3] = 27;
            dt.Rows.Add(oItem);


            GridView gv = new GridView();
            gv.HeaderStyle.BackColor = System.Drawing.Color.CornflowerBlue;
            gv.HeaderStyle.Font.Bold = true;
            gv.HeaderStyle.ForeColor = System.Drawing.Color.White;
            gv.CellPadding = 5;
            gv.AutoGenerateColumns = false;

            BoundField nameColumn = new BoundField();
            nameColumn.DataField = "FirstName";
            nameColumn.HeaderText = "First Name";
            gv.Columns.Add(nameColumn);

            nameColumn = new BoundField();
            nameColumn.DataField = "LastName";
            nameColumn.HeaderText = "Last Name";
            gv.Columns.Add(nameColumn);

            nameColumn = new BoundField();
            nameColumn.DataField = "Age";
            nameColumn.HeaderText = "Age";
            gv.Columns.Add(nameColumn);

            // Here is template column portion
            TemplateField TmpCol = new TemplateField();
            TmpCol.HeaderText = "Click Me";
            gv.Columns.Add(TmpCol);
            TmpCol.ItemTemplate = new TemplateHandler();

            gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);

            gv.DataSource = dt;
            gv.DataBind();

            PlaceHolder1.Controls.Add(gv);
    }

Note: You need to create & bind the GridView in every postback.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim dt As DataTable = New DataTable()

        dt.Columns.Add("ID", System.Type.GetType("System.Int64"))
        dt.Columns.Add("FirstName")
        dt.Columns.Add("LastName")
        dt.Columns.Add("Age", System.Type.GetType("System.Int64"))

        Dim oItem As DataRow = dt.NewRow()
        oItem(0) = "1000"
        oItem(1) = "Shawpnendu"
        oItem(2) = "Bikash"
        oItem(3) = 32
        dt.Rows.Add(oItem)

        oItem = dt.NewRow()
        oItem(0) = "2000"
        oItem(1) = "Bimalendu"
        oItem(2) = "Bikash"
        oItem(3) = 27
        dt.Rows.Add(oItem)


        Dim gv As GridView = New GridView()
        gv.HeaderStyle.BackColor = System.Drawing.Color.CornflowerBlue
        gv.HeaderStyle.Font.Bold = True
        gv.HeaderStyle.ForeColor = System.Drawing.Color.White
        gv.CellPadding = 5
        gv.AutoGenerateColumns = False

        Dim nameColumn As BoundField = New BoundField()
        nameColumn.DataField = "FirstName"
        nameColumn.HeaderText = "First Name"
        gv.Columns.Add(nameColumn)

        nameColumn = New BoundField()
        nameColumn.DataField = "LastName"
        nameColumn.HeaderText = "Last Name"
        gv.Columns.Add(nameColumn)

        nameColumn = New BoundField()
        nameColumn.DataField = "Age"
        nameColumn.HeaderText = "Age"
        gv.Columns.Add(nameColumn)

        'Here is template column portion
        Dim TmpCol As TemplateField = New TemplateField()
        TmpCol.HeaderText = "Click Me"
        gv.Columns.Add(TmpCol)
        TmpCol.ItemTemplate = New TemplateHandler()

        AddHandler gv.RowDataBound, AddressOf Me.gv_RowDataBound

        gv.DataSource = dt
        gv.DataBind()

        PlaceHolder1.Controls.Add(gv)
    End Sub

Note: You need to create & bind the GridView in every postback.

Now Add GridView RowDataBound Handler:
Basically from this section we will assign the ID value to the Template Column Button CommandName property. So that under Button Click event you can get the corresponding GridViewRow ID & can manipulate logic as per your requirement.

C# Code:

    private void gv_RowDataBound(Object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
            ((Button)e.Row.FindControl("cmd")).CommandName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
        // Assigning the ID column value into the Button CommandName value. So that we can identify which row we need to work.
        // Its an alternative of DataKeyNames
    }

VB.Net Code:

    Private Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs)

        If e.Row.RowType = DataControlRowType.DataRow Then
            CType(e.Row.FindControl("cmd"), Button).CommandName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"))
            'Assigning the ID column value into the Button CommandName value. So that we can identify which row we need to work.
            'Its an alternative of DataKeyNames
        End If

    End Sub

Now run the page & click on the Button that i have added in a template column will show you the corresponding GridViewRow ID. Experiment the example that I have shown, hope you will achieve your client target.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code