tags:

views:

1086

answers:

4

Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.


private TreeNode AddNodeForCore(TreeNode root, Core c) {
    string key = GetImageKey(c);
    TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key);
    t.Tag = c;
    return t;
}

Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.

Edit:
My google-fu is weak. Can't believe I didn't find that answer myself.

+2  A: 

A quick google search found this answer: http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&PostID=965968

Quote from that page:

If the Form containing the TreeView is instantiated in the add-in startup function as below, the icons appear!

public partial class ThisApplication
{
    Form1 frm;

    private void ThisApplication_Startup(object sender, System.EventArgs e)
    {
        frm  = new Form1();
        frm.Show();

    }

BUT, if instantiated with the class, as below:

public partial class ThisApplication
{
    Form1 frm = new Form1();


    private void ThisApplication_Startup(object sender, System.EventArgs e)
    {
                    frm.Show();

    }

Then they do NOT appear. Furthermore, if "VisualStyles" (new with XP) are disabled, the icons work in both instances.

VVS
+6  A: 

The helpful bit of the googled posts above is in fact:

"This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Program.cs avoids this. Thanks for posting back!"

So basically, guarantee that Application.EnableVisualStyles() is called before you initialise your imagelist.

Matt Jacobsen
Ah, you're right. This is indeed the more interesting fact.
VVS
+1  A: 

According to the Add method section in MSDN library, you need to fill both TreeView.ImageList and TreeView.SelectedImageList since the fourth arguments refers to the second list.

If this bug happens when you select a node, then look no further.

Johan Buret
A: 

The solution posted by Yossarian nor the popular "Call Application.DoEvents() between Application.EnableVisualStyles() and Application.Run()" worked for me.

After much flailing, gnashing of teeth, and Googling, the solution posted by Addy Santo did the trick.

Richard Morgan