Click here to Skip to main content
15,891,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to List<string>, with the following contents (let's say):

C#
List<string> listA = new List<string>();
List<string> listB = new List<string>();

listA.Add("main1");
listA.Add("main2");
listA.Add("main3");

listB.Add("sub1");
listB.Add("sub2");
listB.Add("sub3");



Now. Here comes where I stuck:

I would like to have the following TreeView:

HTML
|
|-main1-|
|       |-sub1
|       |-sub2
|       |-sub3
|
|-main2-|
|       |-sub1
|       |-sub2
|       |-sub3
|
|-main3-|
|       |-sub1
|       |-sub2
|       |-sub3



I wanna use foreach loop for each Lists. The following code gives me error:

C#
foreach (string mains in listA)
{
    TreeNode node = new TreeNode(mains);
    
    foreach (string subs in listB)
    {
        TreeNode node2 = new TreeNode(subs);

        treeView.Nodes[mains].Nodes.Add(node2);
    }

    treeView.Nodes.Add(node);
}


The error is in the inner foreach, but dunno why... The tree hierarchy is being made as I like. Please help me correcting this loop.

Thanks
Posted

You could simplify this:
C#
private void makeTree(List<string> headings, List<string> items)
{
    foreach (var s0 in headings)
    {
       TreeNode newNode = new TreeNode(s0);
       treeView1.Nodes.Add(newNode);

       foreach (var s1 in items)
       {
           newNode.Nodes.Add(new TreeNode(s1));
       }
    }
}
You'd call it like this:
C#
makeTree(
    new List<string> {"one", "two", "three"},
    new List<string> {"sub1", "sub2"});
 
Share this answer
 
ok, I got it finally... Wrong ordering and do not need two TreeNode. So the correct is:

C#
foreach (string mains in listA)
            {
                TreeNode node = new TreeNode(mains);
                treeView1.Nodes.Add(node);

                foreach (string subs in listB)
                {
                    node.Nodes.Add(subs);
                }

                
            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900