Friday, August 03, 2007

Dynamic Template Columns in the ASP.NET 2.0 GridView Control: Part 1

Recently I was involved in a project where we needed to present the results of a database query as part of an ASP.NET application. It was such that the user can select grid columns and the type of the columns also Differentiating depending on the requirement. It may be a button, column, editable column (text box,check box,etc...) It was not known until runtime how many columns has to display, which columns has to display or which SQL query is needed to satisfy the search criteria. So I had to use dynamics template coloumns for the editable coloumns.

A GridView template is a class that implements the ITemplate interface. It defines the controls that will be displayed on the GridView in a column.I thought it's worthwhile to share it here.


// Class for define Template, this class will added to your app_Code folder.
public class SampleTemplate : ITemplate
{
private string _DataField;

public
SampleTemplate (string DataField)
{
this._DataField = DataField;
}

public void InstantiateIn(Control container)
{
TextBox txtItemVal = new TextBox();
txtItemVal.DataBinding += new EventHandler(this.OnDataBinding);
txtItemVal .ID = "txtItemVal";
container.Controls.Add(
txtItemVal);
}

public void OnDataBinding(object sender, EventArgs e)
{
TextBox TXT = (TextBox)sender;
GridViewRow container = (GridViewRow)TXT.NamingContainer;
string id = ((DataRowView)container.DataItem)[_DataField].ToString();
TXT.Text= id;

}
}



Adding template to your grid.code behind file.In my case i am going through a for loop with in the user datacolumns datatable and adding coloumns to gridview.

TemplateField tmpItem= new TemplateField();

// you have to specify column name as "datafield" here.as for the gridview data source.lets say you //have Employee datatable.and you want to show Empage in this template coloumn.then you should //use empAge as your dataField

SampleTemplate TEMP1 = new SampleTemplate ("Empage");
tmpUnits.HeaderText = "Employee Age"
tmpUnits.ItemTemplate = TEMP1;
gvTransaction.Columns.Add(
tmpItem);

Thats it.Hope this will help you one day.And there's a another way also.will tell you latter. ;)



3 comments:

Raju.M said...

Thankx good post. but it have some problem.i think it was my mistake,first i add one data table,its contain too large data. so i change the table, but i still get the older table contents?? and i do not get page load for next time i run my code

Beladev said...

Thanks a lot.. Keep Posting Good articles like this..

Anonymous said...

Yes, i tried to use the same way and i meet the same problem that getting old data. I change the data, but data table cannot be changed. I think write some code for changing data table's data. However good article =))