Click here to Skip to main content
11,480,626 members (63,209 online)
Click here to Skip to main content

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

, 29 May 2004 CPOL 423.6K 4.1K 76
Rate this:
Please Sign up or sign in to vote.
Creating Template Columns in runtime and data binding.

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. Smile | :)

  • 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)

Share

About the Author

R. Senthil Kumaran
Architect Tesco HSC
India India
Am a C#.Net, ASP.Net, SQL Server Professional
Intrested in Music, Cricket, and exploring new ideas...

Comments and Discussions

 
QuestionMessage Automatically Removed Pin
8-Jul-14 4:22
professionalJohar Saifuddin Mandav Wala8-Jul-14 4:22 
GeneralMy vote of 5 Pin
manoj kumar choubey7-Feb-12 20:32
membermanoj kumar choubey7-Feb-12 20:32 
GeneralRetreiving data from added Templatecolumn Pin
skan8126-Sep-09 20:39
memberskan8126-Sep-09 20:39 
GeneralDrop Down Box Pin
Haseeb Hassan23-Mar-09 18:45
memberHaseeb Hassan23-Mar-09 18:45 
Questionhow to write databinding code in WCF Pin
preetej21-May-08 2:55
memberpreetej21-May-08 2:55 
Generaldatagrid using xml database Pin
canceriandebu9-May-08 0:46
membercanceriandebu9-May-08 0:46 
Questioncreate datagrid dynamicaly with templet control in asp.net(c#) Pin
suny12326-Aug-07 5:50
membersuny12326-Aug-07 5:50 
GeneralCreating template columns at runtime Pin
Adeel Ijaz14-Aug-07 19:47
memberAdeel Ijaz14-Aug-07 19:47 
GeneralRe: Creating template columns at runtime Pin
Govind Raj4-Sep-07 22:25
memberGovind Raj4-Sep-07 22:25 
GeneralFiltering files Pin
suparichit9-Jul-07 3:12
membersuparichit9-Jul-07 3:12 
GeneralProblem with Databinnding Pin
Malini8220-Jun-07 2:47
memberMalini8220-Jun-07 2:47 
GeneralRe: Problem with Databinnding Pin
Govind Raj4-Sep-07 22:29
memberGovind Raj4-Sep-07 22:29 
GeneralDatbinding twice Pin
Malini8220-Jun-07 2:40
memberMalini8220-Jun-07 2:40 
QuestionSub columns with c#.net for Pocket PC Pin
urairat22-Apr-07 19:56
memberurairat22-Apr-07 19:56 
GeneralCreating dynamic EditCommandColumn in vb.net 1.1 Pin
dotnet_lover14-Mar-07 3:16
memberdotnet_lover14-Mar-07 3:16 
AnswerRe: Creating dynamic EditCommandColumn in vb.net 1.1 Pin
R. Senthil Kumaran30-Mar-07 17:34
memberR. Senthil Kumaran30-Mar-07 17:34 
GeneralI hope to use this class but i failed Pin
ko3maia4-Nov-06 23:34
memberko3maia4-Nov-06 23:34 
AnswerRe: I hope to use this class but i failed Pin
R. Senthil Kumaran6-Mar-07 16:48
memberR. Senthil Kumaran6-Mar-07 16:48 
QuestionHow do we bind data to the controls in the in the template columns of this runtime datagrid? [modified] Pin
svbala11-Aug-06 10:08
membersvbala11-Aug-06 10:08 
GeneralEnlazar Diferentes datos Pin
armandog769-Feb-06 13:17
memberarmandog769-Feb-06 13:17 
GeneralRe: Enlazar Diferentes datos Pin
Eponine27-Feb-06 5:03
memberEponine27-Feb-06 5:03 
QuestionRenderControl return NULL Pin
Stefantz29-Sep-05 2:49
memberStefantz29-Sep-05 2:49 
GeneralNothing comes back in OnItemCommand Pin
Rruedi8-Apr-05 0:04
memberRruedi8-Apr-05 0:04 
GeneralRe: Nothing comes back in OnItemCommand Pin
Rruedi8-Apr-05 0:13
memberRruedi8-Apr-05 0:13 
GeneralRe: Nothing comes back in OnItemCommand Pin
Member 47749642-Dec-08 0:16
memberMember 47749642-Dec-08 0:16 
QuestionDataGrid Template Columns with Hyperlink : how to bind data ? Pin
betraimummim1-Apr-05 0:12
memberbetraimummim1-Apr-05 0:12 
AnswerRe: DataGrid Template Columns with Hyperlink : how to bind data ? Pin
Rruedi8-Apr-05 0:24
memberRruedi8-Apr-05 0:24 
GeneralUpdateCommand Pin
Rruedi2-Feb-05 6:11
memberRruedi2-Feb-05 6:11 
GeneralRe: UpdateCommand Pin
R. Senthil Kumaran2-Feb-05 18:03
memberR. Senthil Kumaran2-Feb-05 18:03 
GeneralRe: UpdateCommand Pin
Rruedi3-Feb-05 1:42
memberRruedi3-Feb-05 1:42 
GeneralRe: UpdateCommand Pin
Dhyan Das9-Feb-05 22:56
memberDhyan Das9-Feb-05 22:56 
GeneralRe: UpdateCommand Pin
Kidan15-Sep-05 5:35
memberKidan15-Sep-05 5:35 
GeneralCustom object binding Pin
amir_shitrit4-Jan-05 8:41
memberamir_shitrit4-Jan-05 8:41 
GeneralRe: Custom object binding Pin
Anonymous6-Jan-05 23:06
sussAnonymous6-Jan-05 23:06 
GeneralRe: Custom object binding Pin
amir_shitrit7-Jan-05 1:14
memberamir_shitrit7-Jan-05 1:14 
QuestionHow to get to dropdownlist's SelectedIndexChnaged event Pin
guyinfun24-Nov-04 12:45
memberguyinfun24-Nov-04 12:45 
AnswerRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
R. Senthil Kumaran24-Nov-04 13:51
memberR. Senthil Kumaran24-Nov-04 13:51 
GeneralRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
Talha Anwer25-Feb-05 9:59
memberTalha Anwer25-Feb-05 9:59 
GeneralRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
guyinfun26-Jun-05 8:30
memberguyinfun26-Jun-05 8:30 
GeneralRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
allym8126-Sep-05 4:53
memberallym8126-Sep-05 4:53 
GeneralRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
cac_31-Oct-06 15:06
membercac_31-Oct-06 15:06 
GeneralRe: How to get to dropdownlist's SelectedIndexChnaged event Pin
rajan_dce22-Jan-07 6:48
memberrajan_dce22-Jan-07 6:48 
QuestionHow to name the group Pin
luiz.ragazzi19-Oct-04 9:39
memberluiz.ragazzi19-Oct-04 9:39 
AnswerRe: How to name the group Pin
R. Senthil Kumaran20-Oct-04 22:57
memberR. Senthil Kumaran20-Oct-04 22:57 
GeneralRe: How to name the group Pin
luiz.ragazzi21-Oct-04 5:51
memberluiz.ragazzi21-Oct-04 5:51 
Generalusing DataFormatString Pin
anilnair_m7-Oct-04 2:25
memberanilnair_m7-Oct-04 2:25 
GeneralRe: using DataFormatString Pin
R. Senthil Kumaran8-Oct-04 4:30
memberR. Senthil Kumaran8-Oct-04 4:30 
GeneralAdding an Item to the drop down Pin
AndreaWil4-Aug-04 16:00
memberAndreaWil4-Aug-04 16:00 
GeneralRe: Adding an Item to the drop down Pin
R. Senthil Kumaran4-Aug-04 19:42
memberR. Senthil Kumaran4-Aug-04 19:42 
GeneralRe: Adding an Item to the drop down Pin
AndreaWil4-Aug-04 20:05
memberAndreaWil4-Aug-04 20: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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 30 May 2004
Article Copyright 2004 by R. Senthil Kumaran
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid