项目中需要给Repeater动态加载模版,但是foreach循环RepeaterItem后却找不到任何控件。
贴代码:
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);
Literal lblOID = new Literal();
var strOid = Mylist.FirstOrDefault(s => string.Compare(s, "oid", true) == 0);
if (!string.IsNullOrEmpty(strOid))
{
lblOID.Text = strOid;
lblOID.ID = "lbl_" + strOid.ToUpper();
lblOID.Visible = false;
td1.Controls.Add(lblOID);
}
tr.Controls.Add(td1);
HtmlGenericControl td2;
Mylist.ForEach(str => {
if (string.Compare(str, "oid", true) != 0)
{
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)
{
CheckBox chk = (CheckBox)e.Item.FindControl("chk");
chk.ID=DataBinder.Eval(((RepeaterItem)chk.NamingContainer).DataItem, "OID").ToString();
Mylist.ForEach(str =>
{
//if (string.Compare(str, "oid", true) != 0)
//{
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 = content.GetContent(strWhere, 0, 20, pageIndex, "", 0);
repWOList.DataBind();
绑完数据后,点击一按钮想循环取得Repeater中的CheckBox控件,但是取不到,Item里面的控件数为0,我在Templete中加的都是服务器控件啊,怎么的也不至于为0吧:
先调试一下有没有真正的获取到数据,
您不如不回答