Total Pageviews
Friday, August 7, 2009
GridView with Dynamic columns
To Create dynamic columns in gridview, use template control to create dynamic colums.
Following is the simple example which will demonstrate the DataGridTemplate class which is inherited from ITemplate which is base class of all template control.
This is the definition of the Template for the columns. Ignore the fact that it is called DataGridTemplate. This used to be a DataGrid, but now it's a GridView, and I just now noticed the name hasn't changed. :)
public class DataGridTemplate : ITemplate
{
private ListItemType pTemplateType;
private string pColumnName;
private int pTraitID;
public int TraitID
{
get { return pTraitID; }
set { pTraitID = value; }
}
private List pCategoryList = new List();
public DataGridTemplate(ListItemType type, string colname, int traitID, List scoreCats)
{
pTemplateType = type;
pColumnName = colname;
pTraitID = traitID;
pCategoryList = scoreCats;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
switch (pTemplateType)
{
case ListItemType.Header:
lc.Text = "" + pColumnName + "";
container.Controls.Add(lc);
break;
case ListItemType.Item:
Label lbl = new Label();
lbl.Visible = false;
lbl.Text = TraitID.ToString();
container.Controls.Add(lbl);
RadioButtonList rbl = new RadioButtonList();
rbl.ID = "rbl" + pColumnName;
for (int i = 0; i < pCategoryList.Count; i++)
{
rbl.Items.Insert(i, (string)pCategoryList[i]);
}
TextBox txtComments = new TextBox();
txtComments.ID = "txt" + pTraitID;
txtComments.TextMode = TextBoxMode.MultiLine;
txtComments.Rows = 4;
txtComments.Columns = 30;
container.Controls.Add(rbl);
container.Controls.Add(txtComments);
break;
}
}
}
You need to re-create any dynamically generated controls after a postback because unlike static controls they are not instantiated automatically. So, whatever code you have that generates dynamic columns, be sure to run it on Page_Load so it runs after a postback as well as on the inital request.
Dynamic controls is an area that is covered in many ASP.NET sites, like the Code Project, and many ASP.NET books cover it very well too.
Happy Programming
Subscribe to:
Post Comments (Atom)
Blog Archive
Ideal SQL Query For Handling Error & Transcation in MS SQL
BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...
-
All we need to use the Custom paging in grid view without object data source. Here i am going to explain my code which is used in custom pa...
-
One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to m...
-
using System.Data; using System.Data.SqlClient; using System.Text; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; ...
No comments:
Post a Comment