Click here to Skip to main content
Licence CPOL
First Posted 29 May 2004
Views 385,484
Downloads 3,385
Bookmarked 73 times

DataGrid Template Columns creation in Runtime (using C#) and DataBinding

By R. Senthil Kumaran | 29 May 2004
Creating Template Columns in runtime and data binding.
4 votes, 9.1%
1
5 votes, 11.4%
2
4 votes, 9.1%
3
8 votes, 18.2%
4
23 votes, 52.3%
5
4.11/5 - 44 votes
4 removed
μ 3.88, σa 2.44 [?]

Introduction

Here is a code where you can create a DataGrid at runtime with Template Columns with all types of templates (ItemTemplate, EditItemTemplate, HeaderTemplate, FooterTemplate) and also bind the templates with data.

Creating a grid dynamically with bound columns and even with Button column is simple, but with Template columns, it is quite complicated. Here is a clean solution for the same. :)

  • Create a grid and declare columns.
  • Class file should be inherited from ITemplate for creating templates.
  • Add all columns to the grid.
  • Create events.
  • Fill the grid.
  • Write code for databinding columns in ItemDataBound event.
  • Execute it!

Creating a Grid and declaring columns:

dgRt.ID="dgRt1";//Grid Settings
dgRt.AutoGenerateColumns=true;
dgRt.AllowPaging=true;
dgRt.ShowFooter=true;
dgRt.ShowHeader=true;
declare Columns:

BoundColumn bcl1 = new BoundColumn();

//columns Decalration

TemplateColumn tcl1 = new TemplateColumn();
TemplateColumn tcl2 = new TemplateColumn();
TemplateColumn tcl3 = new TemplateColumn();
TemplateColumn tcl4 = new TemplateColumn();
TemplateColumn tcl5 = new TemplateColumn();
TemplateColumn tcl6 = new TemplateColumn();
TemplateColumn tcl7 = new TemplateColumn();
TemplateColumn tcl8 = new TemplateColumn();
TemplateColumn tcl9 = new TemplateColumn();
TemplateColumn tcl10 = new TemplateColumn();
TemplateColumn tcl11 = new TemplateColumn();

EditCommandColumn ecol1=new EditCommandColumn();

Class File Inherited from ITemplate for Creating Templates:

You need to write a separate class file which inherits the ITemplate interface to create the templates. We have to create a method InstantiateIn which is necessary because of the inheritance from the Itemplate. This gives you the column created with the specified control needed to be added in it. Create an event DataBinding for the control being created and specify all the actions that need to be done there.

Here, I am writing a code to create an EditItemTemplate column with drop down list box, and the attached code contains many classes for controls like TextBox, CheckBox, LinkButton, PushButton, and many more...

public class CreateItemTemplateDDL : ITemplate
{
  DataTable dtBind;
  string strddlName;
  string strDataValueField;
  string strDataTextField;

Here, I added the constructor for creating the DDL with value member and text member.

public CreateItemTemplateDDL(string DDLName, 
  string DataValueField, string DataTextField, DataTable DDLSource)
{
  this.dtBind=DDLSource;
  this.strDataValueField=DataValueField;
  this.strDataTextField=DataTextField;
  this.strddlName=DDLName;
}

Here is the code for declaring DataBinding event for the DDL being added. This occurs while DataGrid is being bound.

public void InstantiateIn(Control objContainer)
{
  DropDownList ddl = new DropDownList();
  ddl.DataBinding+=new EventHandler(ddl_DataBinding);
  objContainer.Controls.Add(ddl);
}

Here, you can assign all the properties and every thing else required for the DDL.

private void ddl_DataBinding(object sender, EventArgs e)
{
  DropDownList ddl= (DropDownList)sender;
  ddl.ID=strddlName;
  ddl.DataSource=dtBind;
  ddl.DataValueField=strDataValueField;
  ddl.DataTextField=strDataTextField;

  //ddl.DataBind();
}

More control classes are available in the download. Likewise, you can add more controls to your DataGrid calling the specified classes.

For using this class:

tcl7.ItemTemplate= new CreateItemTemplateDDL("ddlGrid","ID","UserName",dt);

Here, you have added the DDL for the ItemTemplate. You may call the same even if you want a DDL in EditITemTemplate, FooterTemplate, as well in HeaderTemplate too.

Add all Columns to the Grid:

dgRt.Columns.Add(tcl1);
dgRt.Columns.Add(tcl2);
dgRt.Columns.Add(tcl3);
dgRt.Columns.Add(tcl4);
dgRt.Columns.Add(tcl5);
dgRt.Columns.Add(tcl6);
dgRt.Columns.Add(tcl7);
dgRt.Columns.Add(tcl8);
dgRt.Columns.Add(tcl9);
dgRt.Columns.Add(tcl11);
dgRt.Columns.Add(ecol1);
dgRt.Columns.Add(bcl1);

Here by, you have added all the columns to the grid.

Create Events:

After creating grid, if you wish to have some events for it, say you want to bind the grid, then you need to create a ItemDataBound column, need a pager, then have PagedindexChanged event.

dgRt.ItemDataBound+=new DataGridItemEventHandler(dgRt_ItemDataBound);
dgRt.ItemCommand+=new DataGridCommandEventHandler(dgRt_ItemCommand);
dgRt.PageIndexChanged+=new DataGridPageChangedEventHandler(dgRt_PageIndexChanged);
dgRt.EditCommand+=new DataGridCommandEventHandler(dgRt_EditCommand);
dgRt.UpdateCommand+=new DataGridCommandEventHandler(dgRt_UpdateCommand);
dgRt.CancelCommand+=new DataGridCommandEventHandler(dgRt_CancelCommand);

Fill the Grid:

Fill the grid by pulling the data from the database.

private void fillgrid()
{
  SqlConnection cn = new SqlConnection();
  SqlCommand cmd = new SqlCommand();
  cmd.Connection=cn;
  cmd.CommandText="select * from SmpTable order by cm";
  DataSet ds = new DataSet();
  SqlDataAdapter adp = new SqlDataAdapter(cmd);
  cn.ConnectionString= 
    "SERVER=SQLSERVERNAME;DATABASE=TestProject;UID=abcd;PWD=alskdjfh";

  try
  {
    cn.Open();
    adp.Fill(ds);
    dgRt.DataSource=ds.Tables[0];
    dgRt.DataBind();
    cn.Close();
  }
  catch (Exception ex)
  {
    lblError.Text="Error Occured";
  }
}

Write Code for databinding columns in ItemDataBound Event:

private void dgRt_ItemDataBound(object sender, DataGridItemEventArgs e)
{
  if((e.Item.ItemType==ListItemType.Item ) || 
    (e.Item.ItemType==ListItemType.AlternatingItem))
  {
    DropDownList ddlSmp=((DropDownList)e.Item.Cells[7].FindControl("ddlGrid"));
    ddlSmp.DataSource=.DataSource=dt;//your Data Table Name
    ddlSmp.DataValueField="empid";
    ddlSmp.DataTextField="EmpName";
  }
}

That's it! Now, the grid is ready for you.

License

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

About the Author

R. Senthil Kumaran

Architect
Tesco HSC
India India

Member
Am a C#.Net, ASP.Net, SQL Server Professional
Intrested in Music, Cricket, and exploring new ideas...

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 Pinmembermanoj kumar choubey20:32 7 Feb '12  
GeneralRetreiving data from added Templatecolumn Pinmemberskan81220:39 6 Sep '09  
GeneralDrop Down Box PinmemberHaseeb Hassan18:45 23 Mar '09  
Questionhow to write databinding code in WCF Pinmemberpreetej2:55 21 May '08  
Generaldatagrid using xml database Pinmembercanceriandebu0:46 9 May '08  
Questioncreate datagrid dynamicaly with templet control in asp.net(c#) Pinmembersuny1235:50 26 Aug '07  
GeneralCreating template columns at runtime PinmemberAdeel Ijaz19:47 14 Aug '07  
GeneralRe: Creating template columns at runtime PinmemberGovind Raj22:25 4 Sep '07  
GeneralFiltering files Pinmembersuparichit3:12 9 Jul '07  
GeneralProblem with Databinnding PinmemberMalini822:47 20 Jun '07  
GeneralRe: Problem with Databinnding PinmemberGovind Raj22:29 4 Sep '07  
GeneralDatbinding twice PinmemberMalini822:40 20 Jun '07  
QuestionSub columns with c#.net for Pocket PC Pinmemberurairat19:56 22 Apr '07  
I want to add sub columns under columns product.
example
 
Name Product
ProdA ProdB ProdC
DR.A XA XB XC
DR.B CA CB CC
 
I can create columns Product and columsn Name,but have problem with colum PordA ,B and C
 
Please help me
Thank you,

 
thank you

GeneralCreating dynamic EditCommandColumn in vb.net 1.1 Pinmemberdotnet_lover3:16 14 Mar '07  
AnswerRe: Creating dynamic EditCommandColumn in vb.net 1.1 PinmemberR. Senthil Kumaran17:34 30 Mar '07  
GeneralI hope to use this class but i failed Pinmemberko3maia23:34 4 Nov '06  
AnswerRe: I hope to use this class but i failed PinmemberR. Senthil Kumaran16:48 6 Mar '07  
QuestionHow do we bind data to the controls in the in the template columns of this runtime datagrid? [modified] Pinmembersvbala10:08 11 Aug '06  
GeneralEnlazar Diferentes datos Pinmemberarmandog7613:17 9 Feb '06  
GeneralRe: Enlazar Diferentes datos PinmemberEponine5:03 27 Feb '06  
QuestionRenderControl return NULL PinmemberStefantz2:49 29 Sep '05  
GeneralNothing comes back in OnItemCommand PinmemberRruedi0:04 8 Apr '05  
GeneralRe: Nothing comes back in OnItemCommand PinmemberRruedi0:13 8 Apr '05  
GeneralRe: Nothing comes back in OnItemCommand PinmemberMember 47749640:16 2 Dec '08  
QuestionDataGrid Template Columns with Hyperlink : how to bind data ? Pinmemberbetraimummim0:12 1 Apr '05  

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.120210.1 | Last Updated 30 May 2004
Article Copyright 2004 by R. Senthil Kumaran
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid