Adding TemplateField dynamically with entityframework ObjectSet

Posted: Thursday, February 23, 2012 in .NET, asp.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();
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();
}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s