在嵌套中继器中显示分层数据

问题描述:

我的数据库中有一个实体,看起来像这样;在嵌套中继器中显示分层数据

Item 
{ 
    ID, 
    Text, 
    Description, 
    ... 
    ParentID 
} 

Where ParentID引用另一个Item.ID;

我想用ASP.net分级列出这些项目。我假设我想用一个asp:repeater来进行嵌套,但也许不是。如果有更好的选择,我全力支持它。我特别感兴趣的是3层以上的嵌套。

我正在使用linq C#4.0,如果有关系。

TreeView可能是显示分层数据的不错选择。你可以找到很多用linq实体绑定treeview的例子。不过Repeater仍然是一个选择。

下面的文章将有助于有关XML,LINQ和TreeView http://www.4guysfromrolla.com/articles/042308-1.aspx

也有方法可以做到这一点没有XML数据。

你仍然可以使用中继器,如:

<asp:Repeater ID="rpParent" runat="server" OnItemDataBound="rpParent_ItemDataBound"> 
    <ItemTemplate> 
     <%# Eval("Name") %> 
     <asp:Repeater ID="rpChild" runat="server"> 
      <ItemTemplate> 
       <%# Eval("Name") %> 
      </ItemTemplate> 
     </asp:Repeater> 
    </ItemTemplate> 
</asp:Repeater> 

代码背后:

public partial Page{ 
    protected void rpParent_ItemDataBound(object sender, RepeaterEventArgs e){ 
     Item ParentItem = e.Item.DataItem as Item; 
     Repeater rpChild = e.Item.FindControl("rpChild") as Repeater; 
     rpChild.DataSource = context.SelectChildObjectsByParentId(ParentItem.Id); 
     rpChild.DataBind(); 
    } 
} 

这里是你想要做什么非常有用的扩展方法。它可以让你轻松地绑定到一个层次结构,并显示使用一个TreeView(或中继器,如果你想做到这一点):

http://www.scip.be/index.php?Page=ArticlesNET18#AsHierarchy

http://www.scip.be/index.php?Page=ArticlesNET23