Selecting all items in a ListBox Winform Control

.net, c#, winforms

Solution

Call the `BeginUpdate` and `EndUpdate` methods to prevent the drawing/rendering of the control while properties on that control are being set.

Here is the revised code:

public static void SetSelectedAllItems(this ListBox ctl)
{
    ctl.BeginUpdate();

    for (int i = 0; i < ctl.Items.Count; i++)
    {
        ctl.SetSelected(i, true);
    }

    ctl.EndUpdate();
}

You said that you've tried calling `SuspendLayout` and `ResumeLayout`, but that only affects the control's layout events. This pair of methods is used when you want to change a control's position relative to other controls, like when you set the `Size`, `Location`, `Anchor`, or `Dock` properties.

Problem

I'm trying to select all items in ListBox and made this extension method for this purpose: ``` public static void SetSelectedAllItems(this ListBox ctl) { for (int i = 0; i < ctl.Items.Count; i++) { ctl.SetSelected(i, true); } } ``` Problem is that if I have lots of items in the ListBox, it takes a long time to accomplish this task and I can watch how the ListBox is automatically scrolling down and selecting items. Is there a way to temporary pause the update of a control, so that the task would finish faster? I tried using: ``` ctl.SuspendLayout(); for (int i = 0; i < ctl.Items.Count; i++) ... ctl.ResumeLayout(); ``` But that doesn't seem to do anything.

Original source