Monday, July 11, 2005

System.Windows.Forms.TreeView

How often have you been sitting at your computer, working away, when somebody walks up to you and asks you to fix a bug (not that their are ever bugs in your own work). The bug seems fairly trivial, yet it's in code that has been working fine for a long time.

This is exactly what happened to me, and it's only taken myself and another developer 3 days to track down. In the process, I actually found out that I have been "abusing" the treeview control for some time.

Here is a cut down sample of the code which demonstrates the behavior.







Sure, looks good doesn't it... First time the code is ran, it works a treat. Actually, this code has worked really well for several months. That is, until somebody changed a single property on the TreeView control. That's right, just one property... Scrollable = false;

This one small change resulted in the treenodes not displaying at all, but still allowed the nodes to be selected.

Anyway, I have since found a fix for this, which is to wrap the offending Clear and Add(s) with BeginUpdate() and EndUpdate(), problem fixed.

As it turns out, BeginUpdate() and EndUpdate() stop the treeview from redrawing every time the nodes are changed, which from a resources perspective is a good thing. It also fixed my problem (the one with the code, not the one in my head...)

Anyway, I thought I'd share this with you all, and hopefully it will save you a few hours/days of pulling out your hair..

2 comments:

Anonymous said...

This is clearly a bug of some sort. I spent only 2 hours pulling my hair out (I have less hair). It is more crappy code from MS. We build on sand.

leonerdscrew said...

TreeView formatting nodes in C# Windows Forms