ASP.net中的Repeater控件嵌套
非常喜欢使用Repeater控件,它能够生成干净的代码,手写代码写惯了,看着一堆的垃圾代码就头疼,这是我学习时做的一个Demo,留下备忘,应该有更好的代码实现,思考中......
页面代码:
- <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
- <HeaderTemplate><ul></HeaderTemplate>
- <ItemTemplate>
- <li><%# Eval("cate_name") %>
- <asp:Repeater ID="Repeater2" runat="server">
- <HeaderTemplate><ul></HeaderTemplate>
- <ItemTemplate>
- <li><%# Eval("art_title") %></li>
- </ItemTemplate>
- <FooterTemplate></ul></FooterTemplate>
- </asp:Repeater>
- </li>
- </ItemTemplate>
- <FooterTemplate></ul></FooterTemplate>
- </asp:Repeater>
后端代码:
- protected void Page_Load(object sender, EventArgs e)
- {
- if(!IsPostBack)
- {
- using(SqlConnection conn= new SqlConnection())
- {
- conn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString"].ConnectionString;
- conn.Open();
- using(SqlDataAdapter da = new SqlDataAdapter("select * from category",conn))
- {
- DataSet ds = new DataSet();
- da.Fill(ds);
- Repeater1.DataSource = ds;
- Repeater1.DataBind();
- }
- }
- }
- }
- protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
- {
- if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
- {
- Repeater rep = e.Item.FindControl("Repeater2") as Repeater;
- DataRowView rowv = (DataRowView)e.Item.DataItem;
- int cate_id = Convert.ToInt32(rowv["cate_id"]);
- using (SqlConnection conn = new SqlConnection())
- {
- conn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString"].ConnectionString;
- conn.Open();
- using (SqlDataAdapter da = new SqlDataAdapter("select * from article where owner_id=" + cate_id, conn))
- {
- DataSet ds = new DataSet();
- da.Fill(ds);
- rep.DataSource = ds;
- rep.DataBind();
- }
- }
- }
- }
两个Repeater的嵌套,通过ID关联嵌套部分,输出如下: