public partial class 递归2 : System.Web.UI.Page
{
public List<cmodel> list;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rules r = new rules();
list = r.getlist();//读取数据库
this.rep.DataSource = list.Where(x => x.parentid == 0).ToList();//LINQ2OBJECT
this.rep.DataBind();
}
}
protected void rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
Literal l = new Literal();
l.ID = "ul";
l.Text="<ul>";
e.Item.Controls.Add(l);
}
else if (e.Item.ItemType == ListItemType.Footer)
{
Literal l = new Literal();
l.ID = "ul2";
l.Text = "</ul>";
e.Item.Controls.Add(l);
}
else if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int id = (int)DataBinder.Eval(e.Item.DataItem, "id");
Literal li1 = new Literal();
li1.ID = "li1";
li1.Text = "<li>";
e.Item.Controls.Add(li1);
Literal name = new Literal();
name.ID = "n";
name.Text = DataBinder.Eval(e.Item.DataItem, "classname").ToString();
e.Item.Controls.Add(name);
List<cmodel> temp = list.Where(x => x.parentid == id).ToList();//LINQ2OBJECT
if (temp.Count > 0)
{
Repeater r = new Repeater();
TemplateBuilder tb = new TemplateBuilder();
tb.AppendLiteralString("");
r.HeaderTemplate = tb;
r.FooterTemplate = tb;
r.ItemTemplate = tb;
r.ItemDataBound += new RepeaterItemEventHandler(rep_ItemDataBound); //递归核心
r.DataSource = temp;
r.DataBind();
e.Item.Controls.Add(r);
}
Literal li2 = new Literal();
li2.ID = "li2";
li2.Text = "</li>";
e.Item.Controls.Add(li2);
}
}
}