Adding TemplateField dynamically with entityframework ObjectSet

Posted: Thursday, February 23, 2012 in .NET,

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(); = “name” + i.ToString();
p.myCar = new car();
p.myCar.type = “Nissan” + i.ToString();

TemplateField tmp = new TemplateField();
tmp.ItemTemplate = new TemplateData();

GridView1.DataSource = pl;

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

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s