public class CreateItemTemplate : ITemplate
{
//Field to store the ListItemType value
private ListItemType myListItemType;
public CreateItemTemplate()
{
//
// TODO: Add default constructor logic here
//
}
//Parameterrised constructor
public CreateItemTemplate(ListItemType Item)
{
myListItemType= Item;
}
//Overwrite the InstantiateIn() function of the ITemplate interface.
public void InstantiateIn(System.Web.UI.Control container)
{
//Code to create the ItemTemplate and its field.
if (myListItemType== ListItemType.Item)
{
TextBox txtCashCheque = new TextBox();
container.Controls.Add(txtCashCheque);
}
}
}
Step 2:
- Create an object of the GridView.
- Create an object of the TemplateField.
- Set it's Header-Text and other properties as necessary.
Eg-
GridView gdDynamicGrid = new GridView();
TemplateField tfObject = new TemplateField();
tfObject.HeaderText = "Header Text";
tfObject.HeaderStyle.Width = Unit.Percentage(30);
Step 3:
- Then create a new object of this class and pass the type of item you want to create as the parameter to the constructor.
- Set the ItemTemplate property of the TemplateField to the newly created object.
- Then add this TemplateField object to the GridView object.
Eg-
tfObject.ItemTemplate = new CreateItemTemplate(ListItemType.Item);
gdExportFile.Columns.Add(tfObject);
Wow..now your TemplateField is created successfully.
N.B. - In this example I have created only a ItemTemplate inside a TemplateField. If you need then you can create other types of templates. For that you have to check for the ListItemType for any specific Item and add specific controls accordingly. Then during the creation of the object of the class you have to pass the respective ListItemType as an parameter to the class constructor as described in the below example.
Eg-
Changes need in the class -
public void InstantiateIn(System.Web.UI.Control container)
{
//Code to create the ItemTemplate and its field.
if (myListItemType== ListItemType.Item)
{
TextBox txtCashCheque = new TextBox();
container.Controls.Add(txtCashCheque);
}
//Code to create the HeaderTemplate and its field.
if (myListItemType== ListItemType.Header)
{
Label lblTest = new Label();
lblTest.Text = "Header Text";
container.Controls.Add(lblTest);
}
//Code to create the FooterTemplate and its field.
if (myListItemType== ListItemType.Footer)
{
Label lblTest = new Label();
lblTest.Text = "Footer Text";
container.Controls.Add(lblTest);
}
}
Changes need in the code behind file -
tfObject.HeaderTemplate = new CreateItemTemplate(ListItemType.Header);
tfObject.ItemTemplate = new CreateItemTemplate(ListItemType.Item);
tfObject.FooterTemplate = new CreateItemTemplate(ListItemType.Footer);
Hope you find it interesting.