treeview automatically selects first node, even when a different one is clicked on

A

AndrewDucker

If I set up a treeview with two node in it, and then click on the
second one, the AfterSelect fires _twice_ - once for the first node,
once for the second node.

Can anyone explain why it fires for the first node, and how I can make
it stop?

Cheers,

Andy D

Code to show it happening (presumes a button called button1, a treeview
called treeView1 and a textbox called textBox1):

private void button1_Click(object sender, System.EventArgs e)
{
TreeNode n = new TreeNode("Test1");
treeView1.Nodes.Add(n);
n = new TreeNode("Test2");
treeView1.Nodes.Add(n);
}

private void treeView1_AfterSelect(object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
textBox1.Text += "/n" + e.Node.Text;
}
 
N

Norman Yuan

Do you mean

1. When you click the SECOND NODE, the AfterSelect event fires twice?

or

2 You click "button1" to add two nodes into TreeView, and then click the
SECOND NODE, these TWO actions causes two AfterSelect events fire?

For case 1, no, it won;t happen.

For case 2, yes, AfterSelect will fire twice, the first one happens when the
first node is added into TreeView. By default, the first note being added to
TreeView is set to Selected=true automatically. If you do not want the first
node being added to TreeView to be selected automaticalled, you can:

private void button1_Click(object sender, System.EventArgs e)
{
TreeNode n = new TreeNode("Test1");
n.Selected=false;
treeView1.Nodes.Add(n);
n = new TreeNode("Test2");
h.Selected=false;
treeView1.Nodes.Add(n);
}

So that after all nodes being added to TreeView, no node is selected.

The same thing also applies to ListView.
 

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