tags:

views:

34

answers:

2

I have a entity in my database that looks like this;

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

Where ParentID references another Item.ID;

I want to list these Items hierarchically using ASP.net. I assume I want to use a asp:repeater to do the nesting, but maybe not. If there's a better option I'm all for it. I'm specifically interested in 3+ levels of nesting.

I'm using linq C# 4.0 if that matters.

A: 

TreeView might be a good choice for displaying hierarchical data. You can find lots of example for binding treeview with linq entities. However Repeater is still a choice.

The article below will be helpful about XML, LINQ and TreeView http://www.4guysfromrolla.com/articles/042308-1.aspx

There are also ways to do this without XML Data.

You can still use Repeater like:

<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>

Code Behind:

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();
    }
}
Musa Hafalır
A: 

Here is a pretty useful extension method for what you're trying to do. It will let you easily bind to a heirarchy and display using a treeview (or repeater if you want to do that too):

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

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

Ocelot20