views:

390

answers:

4

Hi, I would really need to programatically click on all nodes in the collection, but I cannot see the way how to do it. I end up with trying to call Node_Click event but I dont know how to use arguments. Thank you for your help!

  foreach (TreeNode node in treeView1.Nodes)
        {
          //here I would need to "click" on each node
        }

EDITED: I need to raise TreeNode_After select. Its because treeview represents DB structure and if you click on node, it may or may not have childs (depends on what DB retrieves). This cycle should serve as ExpandAll.

+1  A: 

To cause every node in the tree to get selected, do this:

 void SelectAllNodes(TreeNodeCollection tnc)
 {
     foreach(TreeNode t in tnc)
     {
        treeView1.SelectedNode = t;
        SelectAllNodes(t.Nodes);
     }
 }

EDIT:
It's also worth noting that your code:

 foreach (TreeNode node in treeView1.Nodes)
 {
      //here I would need to "click" on each node
 }

Won't fire on every node in the tree, it will only return the nodes on the uppermost level. So if any of them have child nodes, they wont be seen by your foreach above. If you want to get EVERY node in the whole tree, you will need to recurse through them, like I did in my example above.

Neil N
You are right, I forgot about the "nested" ones. Thanks!
Petr
A: 

You can "fake" the click simply by passing the node into a "handler-like" function:

foreach (TreeNode node in treeView1.Nodes)
{
   node_click(node, null)
}

protected void node_click(object sender, System.EventArgs e )
{
    //...Your code here

}
Dave Swersky
A: 

Well, do you have a TreeView.NodeMouseClick event handler method defined and wired? If you have that method you can just call it in your foreach loop as such:

foreach (TreeNode node in treeView1.Nodes)
{
    treeView1_NodeMouseClick(node, null);
}

above this statement, in my constructor for example, I have this code

treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);

And I have a sloppy event handler like:

public void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    TreeNode node = sender as TreeNode;
    if (node != null)
        MessageBox.Show(node.Text);
}

It should be safe to send in null for the TreeNodeMouseClickEventArgs as long as you don't plan on actually utilizing the event args.

EDITS in response to question edits:

It looks like you should just simply invoke your AfterSelect(...) method via a direct call when your user presses the Expand All button. So, if I am guessing about your architecture properly, you want to add a call to AfterSelect within the click handler of your Expand All button

Matthew Ruston
A: 

Would this achieve what you are looking for?

        foreach (TreeNode node in this.treeView1.Nodes)
        {
            this.treeView1.SelectedNode = node;
        }
Philip Wallace