- About us
GridView is a very powerful and highly customizable control provided by ASP.NET. The process of adding a GridView control dynamically to a page is almost same as of the other controls. But the problem comes when you want to add a TemplateField dynamically to a dynamically created GridView control. This is so because the TemplateField has few child templates which are not very easy to create dynamically.
To achieve this I have found a way which is described below.
- Create a Class which should be inherited from the ITemplate interface.
- Put this class in the same namespace of your project.
- This class should contain a parameterrised constructor. This constructor should take a ListItemType object as its parameter.
- Overwrite the function InstantiateIn() of the ITemplate interface, which takes an container object as its argument.
- In the code check for if the ListItemType object is an Item object or not. If yes then create an object of the control which you want to put in the TeamplateField, set its property and add it to the container object.
public class CreateItemTemplate : ITemplate
//Field to store the ListItemType value
//Overwrite the InstantiateIn() function of the ITemplate interface.
- Create an object of the GridView.
- Create an object of the TemplateField.
- Set it's Header-Text and other properties as necessary.
GridView gdDynamicGrid = new GridView();
TemplateField tfObject = new TemplateField();
tfObject.HeaderText = "Header Text";
tfObject.HeaderStyle.Width = Unit.Percentage(30);
tfObject.ItemTemplate = new CreateItemTemplate(ListItemType.Item);
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.
Changes need in the class -
public void InstantiateIn(System.Web.UI.Control container)
//Code to create the HeaderTemplate and its field.
//Code to create the FooterTemplate and its field.
Changes need in the code behind file -
tfObject.HeaderTemplate = new CreateItemTemplate(ListItemType.Header);
Hope you find it interesting.