Thursday, February 17, 2011

How do I set an image for some but not all nodes in a TreeView?

I have a TreeView windows forms control with an ImageList, and I want some of the nodes to display images, but I want the others to not have images.

I don't want a blank space where the image should be. I don't want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?

From stackoverflow
  • I tried this once and I don't think it is possible.

    If you try to set both ImageKey and ImageIndex to "not set" values the control just defaults ImageIndex to 0. The following code:

    treeView.ImageKey = "Value";
    Debug.WriteLine(treeView.ImageIndex);
    treeView.ImageKey = null;
    Debug.WriteLine(treeView.ImageIndex);
    treeView.ImageIndex = -1;
    Debug.WriteLine(treeView.ImageIndex);
    

    Produces output:

    -1
    0
    0
    

    This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.

  • You need to set imageIndex and selectedImageIndex to a number that is higher than the number of values in your ImageList. For example, if you create this node and add it to your treeview:

    TreeNode node1 = new TreeNode(string.Empty, 12, 12); // imageList1.Count = 5
    

    you will have an invisible TreeNode inserted into your TreeView. I changed the background color of my TreeView and it was still invisible.

    (I googled this for some time, and I eventually found the answer here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html)

0 comments:

Post a Comment