Search code examples
c#treeview

Disable screen updating while collapsing or expanding all treenodes in a treeview


I have created a class that inherits treeview (CustomTreeview), this will be the class I am working in throughout the question. I want some way to stop the CustomTreeview from painting itself and the nodes until all of the collapsing or expanding is complete. I am referring to this as screen updating since I am familiar with that in VBA. I have tried overriding the OnPaint method as well as the OnNodeDraw method. Although, neither the node.toggle method nor the CollapseAll/ExpandAll methods are triggering either of the OnPaint/OnNodeDraw methods. Below is what I tried for both the OnPaint/OnNodeDraw methods (names and inputs obviously were slightly different to satisfy the override).

protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
    if (!collapsing && !expanding)
    {
        base.OnDrawNode(e);
        NotifyNodeDrawn(this, e);
    }
}

The NotifyNodeDrawn triggers an event handler which I subscribe to in a different class to check some logic deciding if it is in expanding or collapsing mode (Boolean values I set by writing over the CollapseAll/ExpandAll methods).

public new void CollapseAll()
{
    collapsing = true;
    base.CollapseAll();
    collapsing = false;
    this.Invalidate();
}
public new void ExpandAll()
{
    expanding = true;
    base.ExpandAll();
    expanding = false;
    this.Invalidate();
}

If this would work the way I wanted it to, then when i call ExpandAll() for example, The nodes would not redraw until the CustomTreeview.Invalidate() is called. Although, as I said before calling ExpandAll/CollapseAll does not enter the OnDrawNode/OnPaint method at all.

Thank you in advance for your help!


Solution

  • Okay, I've been trying to figure this out for days and I finally came across the solution moments after I posted the question. BeginUpdate() stops the control from redrawing until you call EndUpdate(). Simple and effective solution! I will leave this here to hopefully help someone else! This still does not enter the OnDrawNode/OnPaint override if anyone has any solutions to that mystery.

    public new void ExpandAll()
    {
        BeginUpdate();
        expanding = true;
        base.ExpandAll();
        expanding = false;
        EndUpdate();
    }