Repeater嵌套,非常简单

前台代码:

        <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_OnItemDataBound">
            
<ItemTemplate>
                
<p>
                    
<href='test.aspx?Category=<%# Eval("Id") %>'><%# Eval("Id") %></a>
                
</p>
                
<asp:Repeater ID="Repeater2" runat="server">
                    
<ItemTemplate>
                        
<li><href='<%# Eval("href") %>'>
                            
<%# Eval("text")%></a></li>
                    
</ItemTemplate>
                
</asp:Repeater>
            
</ItemTemplate>
        
</asp:Repeater>

 

使用的类结构是这样的,Category类包含了一个Link类的集合

 

    public class Cateogory
    
{
        
public int Id getset; }
        
public List<Link> Links getset; }
    }


    
public class Link
    
{
        
public string href getset; }
        
public string text getset; }
    }

 

为了演示,不从数据库读取,自己填充一些数据

 

        private static List<Cateogory> GetData()
        
{
            List
<Cateogory> categories = new List<Cateogory>();
            
for (int i = 0; i < 5; i++)
            
{
                Cateogory c 
= new Cateogory();
                c.Id 
= i;
                List
<Link> lst = new List<Link>();
                
for (int j = 0; j < 3; j++)
                
{
                    Link l 
= new Link();
                    l.href 
= "test.aspx?Category=" + i + "&Id=" + j;
                    l.text 
= "Cateogory:" + i + ";Id:" + j;
                    lst.Add(l);
                }

                c.Links 
= lst;

                categories.Add(c);
            }

            
return categories;
        }

 

Page_Load的时候绑定Repeater1

 

        protected void Page_Load(object sender, EventArgs e)
        
{
            List
<Cateogory> categories = GetData();

            Repeater1.DataSource 
= categories;
            Repeater1.DataBind();
        }


关键在这里了,Repeater1绑定的时候,方法里要获取子类的集合,如果是数据库,应该是获取Id,再从数据库中根据Id取数据列表.

 

        protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        
{
            
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            
{
                Repeater rpt 
= e.Item.FindControl("Repeater2"as Repeater;
                
if (rpt != null)
                
{
                    Cateogory category 
= e.Item.DataItem as Cateogory;
                    rpt.DataSource 
= category.Links;
                    rpt.DataBind();
                }

            }

        }

 

最后的效果如图:


posted on 2009-03-19 09:33  廖勇军  阅读(553)  评论(3编辑  收藏  举报

导航