Sudhir
Sudhir

Reputation: 91

Image index of TreeView node changes upon selection

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

Upvotes: 9

Views: 13223

Answers (5)

Issam
Issam

Reputation: 11

Just Add this line:

Node.SelectedIndex:=Node.ImageIndex;

Upvotes: 1

Sherif Hamdy
Sherif Hamdy

Reputation: 11

TreeNode tn = new TreeNode();
tn.Text = "NewRecord";
tn.ImageIndex = 1;

treeView.SelectedNode.Nodes.Add(tn);
treeView.SelectedNode = tn;
treeView.SelectedNode.SelectedImageIndex = tn.ImageIndex; // <--- Problem solved
tn.BeginEdit();

Upvotes: 0

Buenjy
Buenjy

Reputation: 300

you can directly do it in the constructor :

TreeNode node = new TreeNode("My treenode", 1, 1);

Upvotes: 1

Ray
Ray

Reputation: 192306

'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.)

Upvotes: 11

Matt Breckon
Matt Breckon

Reputation: 3374

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

Upvotes: 15

Related Questions