Lets say you need to add itemtemplate dynamically to your gridview and also wants to data bind the sub class which loads with your main class.
Ex:- Person.Car.Type
If you bind list of person as the data source, in the data binding event of the control you can simply call
DataBinder.Eval(container.DataItem, “myCar.type”);
This is a sample code you can use .
protected void Page_Load(object sender, EventArgs e)
{
List<person> pl = new List<person>();
for (int i = 0; i < 5; i++)
{
person p = new person();
p.age = i.ToString();
p.name = “name” + i.ToString();
p.myCar = new car();
p.myCar.type = “Nissan” + i.ToString();
pl.Add(p);
}
TemplateField tmp = new TemplateField();
tmp.ItemTemplate = new TemplateData();
GridView1.Columns.Add(tmp);
GridView1.DataSource = pl;
GridView1.DataBind();
}
}
class person
{
public string name { get; set; }
public string age { get; set; }
public car myCar { get; set; }
}
class car
{
public string name { get; set; }
public string type { get; set; }
}
public class TemplateData : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
Label lb = new Label();
lb.ID = “lb”;
lb.DataBinding += new EventHandler(lb_DataBinding);
container.Controls.Add(cmd);
}
void lb_DataBinding(object sender, EventArgs e) {
Label lb = (Label)sender;
GridViewRow container = (GridViewRow)lb.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, “myCar.type”);
lb.Text = dataValue.ToString();
}




[...] Adding TemplateField dynamically with entityframework ObjectSet [...]