Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
Hi, I'm trying in this code to add node from textbox to treeview if this node equal to node that is found in treeview the new node must be next old node and have color yellow the problem when I click to the button nothing happen
C#
for (int i = 0; i < treeView1.Nodes.Count; i++)
           {
               string p = treeView1.Nodes[i].Text;
               if (p == textBox1.Text)
               {
                   treeView1.SelectedNode.NextNode.Nodes.Add(textBox1.Text);
                   treeView1.SelectedNode.BackColor = Color.Yellow;

               }
           }
Posted
Updated 28-Nov-15 21:48pm
v2
Comments
PIEBALDconsult 28-Nov-15 15:00pm    
Use the debugger to inspect the value of p.
Additionally, if you need to do that a lot, then I recommend you use a Dictionary as well as a Treeview and don't iterate the Nodes.
[no name] 28-Nov-15 15:18pm    
I don't think that nothings happens, but it Looks like you add the node to the "root" and not to the node "p ==...". Have a look to this:http://c-treeview.com/[^]
_Tuba 28-Nov-15 15:30pm    
for loop does not complete just int i = 0 and ended
PIEBALDconsult 28-Nov-15 15:34pm    
Are there any existing Nodes?
_Tuba 28-Nov-15 15:39pm    
yes,I'm adding at design time root and sub child

1 solution

Instead of using:

string p = treeView1.Nodes[i].ToString();

use:

string p = treeView1.Nodes[i].Text;

Calling 'ToString on a 'TreeNode will return something like:

"TreeNode: Node0"

I suggest you revise your question and clarify:

0. you say you have sub-nodes, but the 'for loop in your code only enumerates the root-level nodes: is that your intent ?

1. where exactly do you want to insert the new TreeNode ?

2. why would you want to have two TreeNodes with the same visible 'Text property ?

3. what is the role of the 'SelectedNode here, and why do you changes its 'BackColor ?
 
Share this answer
 
Comments
_Tuba 29-Nov-15 3:46am    
thanks can you see my update question
BillWoodruff 29-Nov-15 21:34pm    
Yes, I read your updated question, and it is still unclear to me what you want.

Try answering the three specific questions I asked you in the solution I posted.
_Tuba 29-Nov-15 3:49am    
but I Don't know how can I visit child without Recursive
PIEBALDconsult 29-Nov-15 12:02pm    
You don't want to search the Tree. When you add a Node to the Tree also add it to a Dictionary < string , TreeNode > , then you search the Dictionary instead, it's much faster.
_Tuba 29-Nov-15 12:24pm    
if the node found as child how can I add new node that has the same text as NextNode ? and my code doesn't work :(

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