43

I'm experimenting with a treeview in a little C#/Winforms application. I have programatically assigned an ImageList to the treeview, and all nodes show their icons just fine, but when I click a node, its icon changes (to the very first image in the ImageList). How can I get the icon to remain unchanged?

BTW: The "SelectedImageIndex" is set to "(none)", since I don't really know what to set it to, since the image-index is different for the nodes (i guess?).

UPDATE: Here is the code of the application (I'm using Visual Studio Express 2008):

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            treeView1.BeginUpdate();
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add("root","Project", 0);  

            treeView1.Nodes[0].Nodes.Add("Foo", "Foo", 2);
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Fizz", "Fizz", 3);
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Buzz", "Buzz", 3);

            treeView1.Nodes[0].Nodes.Add("Bar", "Bar", 1);
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Fizz", "Fizz", 2);
            treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Buzz", "Buzz", 3);

            treeView1.EndUpdate();
            treeView1.ImageList = imageList1;
        }
    }
}
S.C. Madsen
  • 5,100
  • 5
  • 32
  • 50

3 Answers3

61

Simply set the SelectedImageIndex for each node to the same value as ImageIndex. So, if you're creating your node programatically:

        TreeNode node = new TreeNode("My Node");
        node.ImageIndex = 1;
        node.SelectedImageIndex = 1;

Or you can specify the whole lot in the constructor:

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

You can do the same thing using the design time editor if you're adding nodes at design time. You just need to set the SelectedImageIndex at the node level and not at the TreeView level.

Matt B
  • 8,315
  • 2
  • 44
  • 65
  • Great, I knew this would be dead-simple, just didn't know where to look. Thanks! (I can't accept this as solution in another 7 minutes, will do so when I can). – S.C. Madsen Aug 05 '10 at 14:03
3

Hi You can also use the below code:

TreeNode Node = eventArgs.Node;
Node.SelectedImageKey = Node.ImageKey;
RekhaShanmugam
  • 177
  • 2
  • 5
0

what can be done here is, we can utilize TreeView's HitTest method which gives the node information at a given point. Then with that info we can reset the Image to previous. Setting SelectedImageIndex to ImageIndex .Like so

var selectedNodeInfo = treeView.HitTest(treeView.PointToClient(Cursor.Position));
selectedNodeInfo.Node.SelectedImageIndex = selectedNodeInfo.Node.ImageIndex;
Sarang M K
  • 261
  • 3
  • 9