最近项目中用到了Repeater的动态加载模版,园子里找了找,发现一篇:http://www.cnblogs.com/xingshao/archive/2010/08/06/1793827.html
参考了下,修改成自己需要的样子,在这记录下。
public class MyTemplate:ITemplate
{ List<string> Mylist; public MyTemplate(Repeater rpt, List<string> list) { Mylist = list; rpt.ItemDataBound += new RepeaterItemEventHandler(rep_ItemDataBound); } public void InstantiateIn(Control container) { HtmlGenericControl tr = new HtmlGenericControl("tr"); CheckBox chk = new CheckBox(); chk.ID = "chk"; HtmlGenericControl td1 = new HtmlGenericControl("td"); td1.Controls.Add(chk); tr.Controls.Add(td1); HtmlGenericControl td2; foreach (var str in Mylist) { Literal lbl = new Literal(); lbl.Text = str; lbl.ID = "lbl_" + str; td2 = new HtmlGenericControl("td"); td2.Controls.Add(lbl); tr.Controls.Add(td2); } container.Controls.Add(tr); } void rep_ItemDataBound(object sender, RepeaterItemEventArgs e) { foreach (var str in Mylist) { Literal lbl = (Literal)e.Item.FindControl("lbl_" + str); lbl.Text = DataBinder.Eval(((RepeaterItem)lbl.NamingContainer).DataItem, lbl.Text).ToString(); } } }
repWOList.ItemTemplate = new MyTemplate(repWOList, listTemp);
repWOList.DataSource =List; repWOList.DataBind();