2014年7月13日 星期日

[RESOLVED] how to create a gridview template field dynamically and add an item template


below is my gridview control




cellspacing="5" onrowdatabound="gvFunctional_RowDataBound">





















































































































my question is if just have a gridview without template fields ,how can i add template field,item template which can have any asp control dynamically from code behind


thanks in advance


jeeva



Hi,


Please try the solution suggested in the below thread


http://forums.asp.net/t/1001702.aspx



Hi,


Because the TemplateField has few child templates which are not very easy to create dynamically.  

To achieve this, please try to refer to the following:


Step 1:  

- 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.


Eg:


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);

Now your TemplateField is created successfully.


Best Regards.

 


 


沒有留言:

張貼留言