Selecting all items in a ListBox Winform Control

99封情书 提交于 2021-02-16 19:38:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15398091/selecting-all-items-in-a-listbox-winform-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!