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";
dgRt.AutoGenerateColumns=true;
dgRt.AllowPaging=true;
dgRt.ShowFooter=true;
dgRt.ShowHeader=true;
declare Columns:
BoundColumn bcl1 = new BoundColumn();
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;
}
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;
ddlSmp.DataValueField="empid";
ddlSmp.DataTextField="EmpName";
}
}
That's it! Now, the grid is ready for you.
|
|
 |
 | Retreiving data from added Templatecolumn skan812 | 20:39 6 Sep '09 |
|
 |
In my project I have to add columns at runtime in the grid(one at a time by clicking some button). Also i have to display all the columns in the edit mode. So while adding a new template column i have set the ItemTemplate property with the text box as follows
Dim tempColumn as New TemplateColumn tempColumn.ItemTemplate = New CreateItemTemplateTextBox("2000","txtAsset", false) Me.dgdAssets.Columns.Add(tempColumn)
It works fine for the first time and displays one column, but next time when i add a new column, i also have to retrieve the values from existing columns in the grid. But on Postback when all the templateColumns which are added in datagrid are not there.
can someone guide me how can i retreive data from added template columns on postback.
Sikandar
|
|
|
|
 |
 | Drop Down Box Haseeb Hassan | 18:45 23 Mar '09 |
|
 |
Dear Sunil
I want to insert a drop down box as a template column. Here the problem i am having that i have aleady set the autopostback of that drop down but now just need the value for the row count. Could you help me with this.
Thanks
Haseeb
|
|
|
|
 |
 | how to write databinding code in WCF preetej | 2:55 21 May '08 |
|
 |
hi all, actually i m new to .net framework3.0 can anyone tell me how to write code in wcf service.cs file where i have to write coding for retreving data from database to datagrid using dataset, i have given connection string in web.config file of wcf
|
|
|
|
 |
 | datagrid using xml database canceriandebu | 0:46 9 May '08 |
|
 |
Hello I am doing a project on desktop email client using C#.net and xml database. I have a grid where i need to display all the mails stored in xml file. In the grid i need to give a checkbox column when the user wants to delete mails he should be able to delete all the mails which are checked.The xml file has mails and each mail has a unique id along with other details.
can some one provide me suitable code
Thanks
|
|
|
|
 |
 | create datagrid dynamicaly with templet control in asp.net(c#) suny123 | 5:50 26 Aug '07 |
|
 |
i want code in c#, to genrate datagrid dynamically which having templet control? can any one help me.........
suny
|
|
|
|
 |
 | Creating template columns at runtime Adeel Ijaz | 19:47 14 Aug '07 |
|
 |
Dear all,
i am using Asp GridView. The data in the GridView is filled at runtime from the database, that is, sometimes the grid has 7 columns sometime 9 (or more/less) depending on the data in the database.
what i want to do is to use as many template columns as there are columns in the Grid. But the problem is that the data comes at runtime so i dont know the exact number of columns that would be made in the Grid.
How can i solve this problem ?
hope to get useful suggestions in reply.
Thankyou
Adeel Ijaz
|
|
|
|
 |
|
 |
Hi Adeel
I hope u have to use AutoGenerateColumns=False in the property of Gridview.Im not sure but surely it will specify the column u want to display.Reply me if any problem occurs.
|
|
|
|
 |
 | Filtering files suparichit | 3:12 9 Jul '07 |
|
 |
Hi,
Anyone have idea about how to filter file types in asp.net file upload control. So that we ask user to select those files from Dialog box instead of regular exp/java script msg box.
Thanks
suparichit
|
|
|
|
 |
 | Problem with Databinnding Malini82 | 2:47 20 Jun '07 |
|
 |
Hi, This is my code ..
SqlConnection ConnectionString; SqlDataAdapter da ; DataSet ds ;
protected void Page_Load(object sender, EventArgs e) { ConnectionString=new SqlConnection("Data Source=Ecom-009;Database=TEST; uid=sa; pwd=ecom"); if (!Page.IsPostBack) { CreateGrid();
Binddata(); }
}
public void CreateGrid() {
DGLeaveList.BorderColor = System.Drawing.Color.Black; DGLeaveList.BackColor = System.Drawing.Color.Wheat; DGLeaveList.PageCount.ToString();
DGLeaveList.Font.Name = System.Drawing.FontStyle.Regular.ToString(); DGLeaveList.BorderWidth = Unit.Pixel(2);
BoundColumn Empnumber = new BoundColumn(); Empnumber.DataField = "EmpNumber"; Empnumber.HeaderText = "Employee Number"; Empnumber.SortExpression = "EmpNumber"; DGLeaveList.Columns.Add(Empnumber);
BoundColumn LeaveFrom = new BoundColumn(); LeaveFrom.DataField = "leaveFrom"; LeaveFrom.HeaderText = "LeaveFrom"; LeaveFrom.SortExpression = "LeaveFrom"; DGLeaveList.Columns.Add(LeaveFrom);
BoundColumn LeaveTo = new BoundColumn(); LeaveTo.DataField = "LeaveTo"; LeaveTo.HeaderText = "LeaveTO"; LeaveTo.SortExpression = "LeaveTo"; DGLeaveList.Columns.Add(LeaveTo);
BoundColumn Reason = new BoundColumn(); Reason.DataField = "Reason"; Reason.HeaderText = "Reason"; Reason.SortExpression = "Reason"; DGLeaveList.Columns.Add(Reason);
BoundColumn Status = new BoundColumn(); Status.DataField = "Status"; Status.HeaderText = "Status"; Status.SortExpression = "Satus"; DGLeaveList.Columns.Add(Status);
ButtonColumn ButtonSelect = new ButtonColumn(); ButtonSelect.ButtonType = ButtonColumnType.PushButton; ButtonSelect.HeaderText = "Select"; ButtonSelect.Text = "Select"; ButtonSelect.CommandName = "Select"; DGLeaveList.Columns.Add(ButtonSelect);
ButtonColumn ButtonEdit = new ButtonColumn(); ButtonEdit.ButtonType = ButtonColumnType.PushButton; ButtonEdit.HeaderText = "Edit"; ButtonEdit.Text = "Edit"; ButtonEdit.CommandName = "Edit"; DGLeaveList.Columns.Add(ButtonEdit);
ButtonColumn ButtonDelete = new ButtonColumn(); ButtonDelete.ButtonType = ButtonColumnType.PushButton; ButtonDelete.HeaderText = "Delete"; ButtonDelete.Text = "Delete"; ButtonDelete.CommandName = "Delete"; DGLeaveList.Columns.Add(ButtonDelete);
}
void Binddata() { DGLeaveList.DataSource = Getdata("Select * from EMSLeaveReq"); DGLeaveList.DataBind();
} DataSet Getdata(string strsql) { da=new SqlDataAdapter(strsql ,ConnectionString); ds = new DataSet(); da.Fill(ds); return ds; }
I was designed the datagrid with c# code and tried to databind with table Emsleavereq . When i was opned the page at Browser i am getting Table with same columns appering Twice .
Any problem with binding
Malini
|
|
|
|
 |
|
 |
Give me a clear view of your project so i could help u out immediately.
|
|
|
|
 |
 | Datbinding twice Malini82 | 2:40 20 Jun '07 |
|
 |
Hi, This is my code ..
SqlConnection ConnectionString; SqlDataAdapter da ; DataSet ds ;
protected void Page_Load(object sender, EventArgs e) { ConnectionString=new SqlConnection("Data Source=Ecom-009;Database=TEST; uid=sa; pwd=ecom"); if (!Page.IsPostBack) { CreateGrid();
Binddata(); }
}
public void CreateGrid() {
DGLeaveList.BorderColor = System.Drawing.Color.Black; DGLeaveList.BackColor = System.Drawing.Color.Wheat; DGLeaveList.PageCount.ToString();
DGLeaveList.Font.Name = System.Drawing.FontStyle.Regular.ToString(); DGLeaveList.BorderWidth = Unit.Pixel(2);
BoundColumn Empnumber = new BoundColumn(); Empnumber.DataField = "EmpNumber"; Empnumber.HeaderText = "Employee Number"; Empnumber.SortExpression = "EmpNumber"; DGLeaveList.Columns.Add(Empnumber);
BoundColumn LeaveFrom = new BoundColumn(); LeaveFrom.DataField = "leaveFrom"; LeaveFrom.HeaderText = "LeaveFrom"; LeaveFrom.SortExpression = "LeaveFrom"; DGLeaveList.Columns.Add(LeaveFrom);
BoundColumn LeaveTo = new BoundColumn(); LeaveTo.DataField = "LeaveTo"; LeaveTo.HeaderText = "LeaveTO"; LeaveTo.SortExpression = "LeaveTo"; DGLeaveList.Columns.Add(LeaveTo);
BoundColumn Reason = new BoundColumn(); Reason.DataField = "Reason"; Reason.HeaderText = "Reason"; Reason.SortExpression = "Reason"; DGLeaveList.Columns.Add(Reason);
BoundColumn Status = new BoundColumn(); Status.DataField = "Status"; Status.HeaderText = "Status"; Status.SortExpression = "Satus"; DGLeaveList.Columns.Add(Status);
ButtonColumn ButtonSelect = new ButtonColumn(); ButtonSelect.ButtonType = ButtonColumnType.PushButton; ButtonSelect.HeaderText = "Select"; ButtonSelect.Text = "Select"; ButtonSelect.CommandName = "Select"; DGLeaveList.Columns.Add(ButtonSelect);
ButtonColumn ButtonEdit = new ButtonColumn(); ButtonEdit.ButtonType = ButtonColumnType.PushButton; ButtonEdit.HeaderText = "Edit"; ButtonEdit.Text = "Edit"; ButtonEdit.CommandName = "Edit"; DGLeaveList.Columns.Add(ButtonEdit);
ButtonColumn ButtonDelete = new ButtonColumn(); ButtonDelete.ButtonType = ButtonColumnType.PushButton; ButtonDelete.HeaderText = "Delete"; ButtonDelete.Text = "Delete"; ButtonDelete.CommandName = "Delete"; DGLeaveList.Columns.Add(ButtonDelete);
}
void Binddata() { DGLeaveList.DataSource = Getdata("Select * from EMSLeaveReq"); DGLeaveList.DataBind();
} DataSet Getdata(string strsql) { da=new SqlDataAdapter(strsql ,ConnectionString); ds = new DataSet(); da.Fill(ds); return ds; }
I was designed the datagrid with c# code and tried to databind with table Emsleavereq . When i was opned the page at Browser i am getting Table with same columns appering Twice .
Any problem with binding
Malii
|
|
|
|
 |
 | Sub columns with c#.net for Pocket PC urairat | 19: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
|
|
|
|
 |
 | Creating dynamic EditCommandColumn in vb.net 1.1 dotnet_lover | 3:16 14 Mar '07 |
|
 |
i m creating dynamic editcommandcolumn using this code
Dim col As New EditCommandColumn col.ButtonType = ButtonColumnType.LinkButton col.HeaderText = "Promotion" col.EditText = " Promotion" Me.dgarea.Columns.Add(col)
now this code works fine but how do i trace it click event i.e.how can i write a function that is called when this link is clicked
|
|
|
|
 |
|
 |
Add a Commandtext to the column and catch it in the Itecommand event!
|
|
|
|
 |
 | I hope to use this class but i failed ko3maia | 23:34 4 Nov '06 |
|
 |
I hope to use this class but i faled please tell me how can i use that class step by step thank u for this class
and i hope to get like this class but it use in windows application
|
|
|
|
 |
|
 |
This is specific to web apllication.
|
|
|
|
 |
 | How do we bind data to the controls in the in the template columns of this runtime datagrid? [modified] svbala | 10:08 11 Aug '06 |
|
 |
Hi Senthil,
How do we bind data to Control in the template column ?
In the sample we pass "Textbox Working" as a static text for a textbox control of a template control.
tcl5.ItemTemplate = new CreateItemTemplateTextBox("Textbox Working","txtGrid1",true);
How do we bind/pass a datatable column to this textbox control of a template control?
Like how we do it in Aspx page using DataBinder.Eval(Container.DataItem contruct
<asp:TemplateColumn HeaderText="Select" HeaderStyle-ForeColor="White" HeaderStyle-Font-Underline="True">
<asp:TextBox ID="txtSSN" runat=server text='<%# DataBinder.Eval(Container.DataItem, "tsSSN") %>' Height="0" Width="0">
I Got the Answer We have to just a the the following Code in the Data binding code.
private void txt_DataBinding(object sender, EventArgs e) { TextBox txt = (TextBox)sender; if(TextMode==true) { txt.TextMode=TextBoxMode.MultiLine; } else { txt.TextMode=TextBoxMode.SingleLine; } txt.ID=strTextBoxName; txt.MaxLength=MaxLength; txt.ReadOnly=ReadOnly; // the Below code DataGridItem container = (DataGridItem)txt.NamingContainer; txt.Text += DataBinder.Eval(container.DataItem, strColumnText); }
-- modified at 11:09 Monday 14th August, 2006
|
|
|
|
 |
 | Enlazar Diferentes datos armandog76 | 13:17 9 Feb '06 |
|
 |
Segun lo veo este ejemplo llena la columna platilla con el mismo dato en todas las filas del datagrid. Estuve buscando pero no pude encontra como enlazarlos a diferentes valores cada fila Por ejemplo cuando se hace en modo de diseño y se enlaza a un campo del datset, la columna toma el valor de la columna del dataset al que se esta enlazando. Y no quiero asignarle el valor a cada columna plantilla de cada fila a pie, por decir con un for ir asignado el valor que le corresponde.
Si alguien pudiera darme una pista
|
|
|
|
 |
|
|
 |
 | RenderControl return NULL Stefantz | 2:49 29 Sep '05 |
|
 |
I successfully created the datagrid at runtime. However when I tried to render the control to HTML using string writer, it return NULL. what happen?
System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter sw = new System.IO.StringWriter(sb); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
dgUpdate.DataSource = arTime; dgUpdate.DataBind(); dg.RenderControl(htw);
dg is datagrid that rendered at runtime.. please advise... thank you..
|
|
|
|
 |
 | Nothing comes back in OnItemCommand Rruedi | 0:04 8 Apr '05 |
|
 |
Hi I build a datagrid completely as custom control without aspx definitions. They are a lot of problems to solve doing this... Sorting, paging, searching, editing works fine. But when I select a row and want to get the row content on the OnItemCommand event the LiteralControls are empty. This is the test:
foreach (TableCell td in e.Item.Cells) { if (td.Controls[0].GetType().Name=="LiteralControl") { zwi+=td.Controls[0].GetType().Name + "=" + ((LiteralControl)td.Controls[0]).Text + " "; } else { zwi+=td.Controls[0].GetType().Name + " "; } } this.SetMessage(zwi);
Do you have any Idea what this could be?
|
|
|
|
 |
|
 |
Uhh ohh, I forgot my UpdateCommand posting in february. Seems to have the same cause, but I tried and searched a lot about EnableViewstate and didn't find anything.:(
|
|
|
|
 |
|
 |
u bind itemcommand by a event handler
dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);
i used it like..
private void dg_ItemCommand(object sender, DataGridCommandEventArgs e) { try { if (e.CommandName == "Remove") { } } catch (Exception ex) { HandleException.ExceptionLogging(ex.Source, ex.Message, true);
}
}
but it is not working. When i click on button mo data display.
|
|
|
|
 |
 | DataGrid Template Columns with Hyperlink : how to bind data ? betraimummim | 0:12 1 Apr '05 |
|
 |
In demo project. I saw all controls for create Template Columns in DataGrid without Hyperlink . I tried to create Template Columns with Hyperlink control but i cant bind data for it . Anybody help me?
|
|
|
|
 |
|
 |
I'm fighting with this too. I wanted to create a LinkButton with a CommandName and in the Databinding fill a CommandArgument (Key of the Row). But it does not work. Another possibility is to define a Button Column in the InitializeComponent (as it is generated in non-runtime):
ButtonColumn selCol = new ButtonColumn(); selCol.CommandName = "DETAIL"; selCol.ButtonType = ButtonColumnType.LinkButton; selCol.Text = "•"; this.Columns.Add(selCol);
My problem is, I want to have a Bullet in the text and not the key(ID) visible as it is when you uncomment the DataTextField. After them you still have the situation, that you can't get the value in the OnItemCommand.:(
|
|
|
|
 |
|
|
Last Updated 30 May 2004 |
Advertise |
Privacy |
Terms of Use |
Copyright ©
CodeProject, 1999-2010