Click here to Skip to main content
Licence 
First Posted 7 Mar 2006
Views 82,178
Downloads 944
Bookmarked 22 times

Create Template column dynamically in DataGrid

By | 7 Mar 2006 | Article
This articles helps in creating template columns dynamically with bound columns using a template class

Sample Image - DynamicTemplateColumnExample.jpg

Introduction

This Article helps in creation of template columns dynamically . I got a condition when i have to display few column values from database and few template (checkbox) column dynamically.

I have created a sample template class which is required in project.Firstly modify template class as per your requirement.As here i have given checkbox as template column example.

Steps to implement code in your project :

1) Set the DataGrid AutoGenerateColumns property to false .

2) Example to Bound the static Columns

<asp:DataGrid id="ItemsGrid" runat="server" OnItemCommand="Grid_CartCommand" AutoGenerateColumns="False"
CellPadding="3" BorderWidth="1px" BorderColor="Black">
<HeaderStyle BackColor="#C0C0FF"></HeaderStyle>
<Columns>
<asp:ButtonColumn Text="Add" ButtonType="PushButton" HeaderText="Add to cart" CommandName="AddToCart"></asp:ButtonColumn>
<asp:ButtonColumn Text="Remove" ButtonType="PushButton" HeaderText="Remove from cart" CommandName="RemoveFromCart"></asp:ButtonColumn>
<asp:BoundColumn DataField="StringValue" HeaderText="Item"></asp:BoundColumn>
<asp:BoundColumn DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>

3) In Page_load add following Code

if (!IsPostBack)
{
// Load this data only once.
ItemsGrid.DataSource= CreateDataSource(); //Function to create dynamic column
ItemsGrid.DataBind();
}

<headERSTYLE BackColor="#C0C0FF"></headERSTYLE><asp:ButtonColumn CommandName="AddToCart" HeaderText="Add to cart" ButtonType="PushButton" Text="Add"></asp:ButtonColumn><asp:ButtonColumn CommandName="RemoveFromCart" HeaderText="Remove from cart" ButtonType="PushButton" Text="Remove"></asp:ButtonColumn><asp:BoundColumn HeaderText="Item" DataField="StringValue"></asp:BoundColumn><asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}">

4) In OnInit() add following code protected void OnInit(EventArgs e)// // CODEGEN: This call is required by the ASP.NET Web Form Designer. //

CreateDataGridColumn();

InitializeComponent();

}

base.OnInit(e);

//-----------------------------------------------------------------------------

public

{

override

{

void CreateDataGridColumn()// Create dynamic column to add to Columns collection. //-----------------------------------------------------------------------------

TemplateColumn tc1 =

//-----Class used named DataGridTempla.cs------

tc1.HeaderTemplate =

tc1.ItemTemplate =

tc1.EditItemTemplate =

tc1.FooterTemplate =

ItemsGrid.Columns.Add(tc1);

new TemplateColumn();new DataGridTempla(ListItemType.Header, "Select1");new DataGridTempla(ListItemType.Item, "Select1");new DataGridTempla(ListItemType.EditItem, "");new DataGridTempla(ListItemType.Footer, "");//-----------------------------------------------------------------------------

TemplateColumn tc2=

tc2.HeaderTemplate=

tc2.ItemTemplate=

ItemsGrid.Columns.Add(tc2);

new TemplateColumn();new DataGridTempla(ListItemType.Header,"Select2");new DataGridTempla(ListItemType.Item,"Select2");//-----------------------------------------------------------------------------

BoundColumn NumberColumn =

NumberColumn.HeaderText="Item Number";

NumberColumn.DataField="IntegerValue";

new BoundColumn();// Add column to Columns collection.

ItemsGrid.Columns.AddAt(2, NumberColumn);

}

</asp:BoundColumn>

//-----------------------------------------------------------------------------

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dolly Jain

Web Developer

India India

Member

Be helpful.When you see a person without a smile ,Give him yours........
 
(Zig Ziglar)

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
QuestionSample discuss PinmemberMiguel Nazario7:12 5 Mar '08  
When i try to make a simple DataGrid using template columns whit dynamic column in code i can't bound columns corretly.
 
very simple in VB code:

' note i'am using for test only access database db1.mdb.
' it have just one table whit a,b,c columns and some random data,
' just for teste.
 
Imports System.Data.OleDb
Imports System.Data
Public Class WebForm1
Inherits System.Web.UI.Page
 
#Region " Web Form Designer Generated Code "
 
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
 
End Sub
 
Protected WithEvents myDataGrid As System.Web.UI.WebControls.DataGrid
Protected strcon As String = "Jet OLEDB:Database Password=;Data Source=C:\Inetpub\wwwroot\testAzamGrid\db1.mdb;Password=;Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;"
Protected dt As DataTable = New DataTable
 
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
 
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
 
#End Region
 
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BuildDataGrid()
End Sub
 
Private Sub BuildDataGrid()
' Fill dt
GetData("a asc")
 
For i As Integer = 0 To dt.Columns.Count - 1
' Creating Template Column
Dim test As TemplateColumn = New TemplateColumn
Dim columnName As String = dt.Columns(i).ColumnName
test.HeaderTemplate = New DataGridTemplate(ListItemType.Header, columnName)
 
'Adding the Rows to the DataGrid
For j As Integer = 0 To dt.Rows.Count - 1
Dim score As String = dt.Rows(j)(i).ToString()
test.ItemTemplate = New DataGridTemplate(ListItemType.Item, score)
Next
myDataGrid.Columns.Add(test)
Next
myDataGrid.DataSource = dt
myDataGrid.DataBind()
End Sub
 
Private Function GetData(ByRef campo As String) As DataTable
Dim cnn As OleDbConnection = New OleDbConnection(strcon)
cnn.Open()
Dim cmd As OleDbCommand = cnn.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "select a,b,c from TB_NOME order by " & campo
 
Dim ad As OleDbDataAdapter = New OleDbDataAdapter(cmd)
'Dim dt As DataTable = New DataTable ' local in use.
 
ad.Fill(dt)
cnn.Close()
Return dt
End Function
 
End Class
 
Public Class DataGridTemplate
Inherits System.Web.UI.Page
Implements ITemplate
 
Public templateType As ListItemType
Public columnName As String
 

Public Sub New(ByVal type As ListItemType, ByVal colname As String)
templateType = type
columnName = colname
End Sub
 
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim lc As Literal = New Literal
Dim lb As LinkButton = New LinkButton
 
Select Case templateType
Case ListItemType.Header
lc.Text = "<B>" + columnName + "</B>"
lb.Text = "Edit"
lb.CommandName = "EditButton"
container.Controls.Add(lb)
container.Controls.Add(lc)
Exit Select
 
Case ListItemType.Item
lc.Text = "Item " + columnName
container.Controls.Add(lc)
Exit Select
 
Case ListItemType.EditItem
Dim tb As TextBox = New TextBox
tb.Text = ""
container.Controls.Add(tb)
Exit Select
 
Case ListItemType.Footer
lc.Text = "<I>" + columnName + "</I>"
container.Controls.Add(lc)
Exit Select
End Select
End Sub
End Class
 
////////////////////////////////
WebForm1.aspx
 
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="testAzamGrid.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
 
<form id="Form1" method="post" runat="server">
<asp:DataGrid ID="myDataGrid" GridLines="Both" AutoGenerateColumns="false" Visible="True" ShowHeader="True" Runat="server"></asp:DataGrid>
</form>
 
</body>
</html>
/////////////////////////////////////////////////

 

do know i this don't work well? Smile | :)
GeneralGr8 Job Done PinsussPreeti Agrawal19:56 13 Dec '07  
GeneralEvents lost: do it Before OnInit PinmemberRicardo Casquete0:27 14 Mar '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
Web01 | 2.5.120529.1 | Last Updated 8 Mar 2006
Article Copyright 2006 by Dolly Jain
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid