how to load a 4 level tree view in asp.net

I have table called Topic whose structure i am sending with this question.
this topic has columns ParentPKey and Pkey.

and I want to load tree some thing like i have given in the code section

now I want to add all those records in to the tree view who has parentkey =0 as the parent node. then I want to add those nodes whose parentpkey = pkey ( of those nodes whose parentkey = 0).

then I want to those nodes whose parentpkey is equal to the nodes which are added in the second step.
and so on so fourth.
my problem here is there might be a chance  that some where in the middle or in the end of records some node come whose parent is on the top of the tree.

right now i am using loops but it totally messed up.
any one could help me here.

-Node1
    -2Node
        -3Node
         -4Node

Open in new window

untitled.JPG
ziorrinfotechAsked:
Who is Participating?
 
Carl TawnConnect With a Mentor Systems and Integration DeveloperCommented:
You could do something along the lines of the following. At the end of this code the "rootNodes" List will contain all of the top-level nodes (i.e. nodes with no parent) with all of their children nested underneath.


Dictionary<int, TreeNode> nodes = new Dictionary<int, TreeNode>();
List<TreeNode> rootNodes = new List<TreeNode>();
 
// i'll assume a data reader as the datasource
while (reader.Read())
{
    TreeNode newNode = new TreeNode(reader.GetString("TopicName");
    int parentId = reader.GetInt32("ParentPKey");
 
    if (nodes.ContainsKey(parentId))
    {
        parent = nodes[parentId];
        parent.Nodes.Add(newNode);
    {
 
    if (parentId == 0)
       rootNodes.Add(newNode);
}

Open in new window

0
 
ctrlctrlCommented:
This is part of the solution I am trying to write
public void PopulateTreeView()
        {
            Dictionary<int, TreeNode> nodes = new Dictionary<int, TreeNode>();
            List<TreeNode> rootNodes = new List<TreeNode>();
 
            SampleDB db = new SampleDB();
            var query = from o in db.OptionsMenu
                        orderby o.MenuID, o.ParentMenuID ascending
                        select o;
            int i = query.Count();
 
 
            if (i > 0)
            {
                foreach(var q in query)
                {
                    TreeNode newNode = new TreeNode(q.MenuName);
                    int parentID = Int32.Parse(q.ParentMenuID.ToString());
 
                    if(nodes.ContainsKey(parentID)
                    {
                        
 
                    }
 
                    }
            }
 
 
 
 
        }

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.