Dynamic TreeNode creation in runtime

E

Ehsan

What i want to achieve(in runtime):
A root named "Home" with nodes added to it named "A","B","C" and so on til
"Z".
I want these subnodes named accordingly Home_A, Home_B and so on, in the
code so they can be accessed like Home_G.Node.Add("bla bla").

Basicly, i'm trying to make a "Register" where you can add names, they're
sorted and put in the correct node in the tree. The sorting part i've
figured out.. I have added the nodes in runtime, "manually", without using
loops but it looks very shabby and takes up alot of code. The loop i've been
trying to get working looks like this:

My aproach:
**************************
trTest.Nodes.Add("Home");
for(int i=65; i<91; i++)
{
string ch = Convert.ToString(Convert.ToChar(i));
string create = "Home_" + ch;
TreeNode (Convert.ToString(create)) = new TreeNode(ch); //Se note
trTest.Nodes[0].Nodes.Add(create);
}
//Note: Well... Since TreeNode is a class.. the context it's given
//... in isn't valid... any ideas, pointers, suggestions?
***************************
 
F

Frank Oquendo

Thus spake Ehsan:
My aproach:
**************************
trTest.Nodes.Add("Home");
for(int i=65; i<91; i++)
{
string ch = Convert.ToString(Convert.ToChar(i));
string create = "Home_" + ch;
TreeNode (Convert.ToString(create)) = new TreeNode(ch); //Se note
trTest.Nodes[0].Nodes.Add(create);
}
//Note: Well... Since TreeNode is a class.. the context it's given
//... in isn't valid... any ideas, pointers, suggestions?
***************************

At this point, there's no need to create a variable with a specific
name:

TreeNode parent = trTest.Nodes.Add("Home"), child;
char suffix;

for (int i = 65; i < 91; i++)
{
suffix = (char) i;
child = parent.Nodes.Add("Home_" + suffix);
// do whatever you need to with child
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top