I can bind a inner object property to gridview using the following setup at design time in an ASP.NET gridview
<asp:TemplateField HeaderText="ObjectName" >
<ItemTemplate>
<%# Eval("Object.property")%>
</ItemTemplate>
</asp:TemplateField>
but what I would like to do know is create this programmatically at runtime
i.e. define my columns, add them to the gridview and then databind
One way would be to create a class that implements ITemplate interface:
public class PropertyTemplate : ITemplate
{
private string _value = string.Empty;
public PropertyTemplate(string propValue)
{
this._value = propValue;
}
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl(this._value));
}
}
Then in your code-behind assing the ItemTemplate
as following:
myTemplateField.ItemTemplate = new PropertyTemplate(myBusinessObject.MyProperty);
Another way would be to use Page.LoadTemplate if your custom template resides in the separate .ascx
file:
myTemplateField.ItemTemplate = Page.LoadTemplate("~/MyTemplate.ascx");
And the .ascx
file will look like:
<%# Eval("MyProperty") %>