views:

722

answers:

3

When I tried using the imagelist in treeview, the image index changes when treenode is clicked. I have no idea why it is happening. Can anyone help me?

Thanks in advance

+1  A: 

You need to set both the ImageIndex and the SelectedImageIndex on the tree node.

Matt Breckon
+1  A: 

'SelectedImageIndex's intent is to allow displaying a different image upon selection than what is set by the 'ImageIndex' for a particular node. To keep these two consistent it is necessary to set them to the same value. This can be done at design time or programmatically depending on your needs.

For example, if the images never change then it is as simple as setting them concurrently when a new node is added to the TreeView:

int myCurrentImageIndex = 0;
TreeNode node = myTreeView.Nodes.Add("new node!");
node.ImageIndex = node.SelectedImageIndex = myCurrentImageIndex;

However, if you do change the ImageIndex value for any reason after its initial creation (such as a response to some kind of user action), then you must also change the SelectedImageIndex as well. Otherwise, they will become inconsistent.

int myNewImageIndex = 1;
node.ImageIndex = node.SelectedImageIndex = myNewImageIndex;

(Note it is not enough to set them to be the same in the event handler of the 'AfterSelect' event. It must be done anywhere in your code where ImageIndex changes.)

Ray Vega
If you're doing an application that presents its structure like a folder, your users will appreciate having the change in image when they've selected a "folder." Just make sure the change isn't too garish or subtle.
Jason D
Ok, I have the same situation. But how do I completely stop this behavior? All my nodes are created during runtime. Tracking the AfterSelect event will give me a way to stop this?
George
A: 

The use of the AfterSelect event is not even necessary if you create your nodes at runtime. You simply set both values when you create the node, as Ray Vega explained.

Marcelo Ruiz