ASP.net中的Repeater控件嵌套

非常喜欢使用Repeater控件,它能够生成干净的代码,手写代码写惯了,看着一堆的垃圾代码就头疼,这是我学习时做的一个Demo,留下备忘,应该有更好的代码实现,思考中......

页面代码:

  1. <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound"> 
  2. <HeaderTemplate><ul></HeaderTemplate> 
  3. <ItemTemplate> 
  4. <li><%# Eval("cate_name") %> 
  5.     <asp:Repeater ID="Repeater2" runat="server"> 
  6.     <HeaderTemplate><ul></HeaderTemplate> 
  7.     <ItemTemplate> 
  8.         <li><%# Eval("art_title") %></li> 
  9.     </ItemTemplate> 
  10.     <FooterTemplate></ul></FooterTemplate> 
  11.     </asp:Repeater> 
  12. </li> 
  13. </ItemTemplate> 
  14. <FooterTemplate></ul></FooterTemplate> 
  15. </asp:Repeater> 

后端代码:

  1. protected void Page_Load(object sender, EventArgs e) 
  2.     if(!IsPostBack) 
  3.     { 
  4.         using(SqlConnection conn= new SqlConnection()) 
  5.         { 
  6.             conn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString"].ConnectionString; 
  7.             conn.Open(); 
  8.             using(SqlDataAdapter da = new SqlDataAdapter("select * from category",conn)) 
  9.             { 
  10.                 DataSet ds = new DataSet(); 
  11.                 da.Fill(ds); 
  12.                 Repeater1.DataSource = ds; 
  13.                 Repeater1.DataBind(); 
  14.             } 
  15.         } 
  16.     } 
  17. protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
  18.     if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
  19.     { 
  20.         Repeater rep = e.Item.FindControl("Repeater2"as Repeater; 
  21.         DataRowView rowv = (DataRowView)e.Item.DataItem; 
  22.         int cate_id = Convert.ToInt32(rowv["cate_id"]); 
  23.         using (SqlConnection conn = new SqlConnection()) 
  24.         { 
  25.             conn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString"].ConnectionString; 
  26.             conn.Open(); 
  27.             using (SqlDataAdapter da = new SqlDataAdapter("select * from article where owner_id=" + cate_id, conn)) 
  28.             { 
  29.                 DataSet ds = new DataSet(); 
  30.                 da.Fill(ds); 
  31.                 rep.DataSource = ds; 
  32.                 rep.DataBind(); 
  33.             } 
  34.         } 
  35.     } 

两个Repeater的嵌套,通过ID关联嵌套部分,输出如下:

posted @ 2009-06-22 12:51  shaoyun  阅读(477)  评论(1编辑  收藏  举报