如何快速选择ListBox中的所有项目?

时间:2016-01-22 18:02:50

标签: c# winforms listbox

我在窗体(Windows窗体)上绑定到数据源(BindingList)有一个ownerdrawn ListBox。 我需要提供一个选项来快速选择所有项目(最多500000)。

这就是我目前正在做的事情:

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

这非常慢,不可接受。有人知道更好的解决方案吗?

5 个答案:

答案 0 :(得分:9)

假设这是Windows Forms问题:Windows窗体将在每个选定项目后绘制更改。要在完成后禁用绘图并启用它,请使用BeginUpdate()EndUpdate()方法。

listBox.BeginUpdate();

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

listBox.EndUpdate();

答案 1 :(得分:1)

您可以尝试listbox.SelectAll();

以下是关于ListBox SelectAll()的微软文档的链接:

https://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selectall(v=vs.110).aspx

答案 2 :(得分:1)

我找不到足够快的方法来接受。 我尝试了BeginUpdate / EndUpdate,它虽然有所帮助,但在Intel Core i5笔记本电脑上仍然花费了4.3秒。 因此,这很me脚,但它可以工作-至少在IDE中可以。 我有一个名为“全选”的按钮,列表框被称为lbxItems。在该按钮的点击事件中,我有:

//save the current scroll position
int iTopIndex = lbxItems.TopIndex;

//select the [0] item (for my purposes this is the top item in the list)
lbxItems.SetSelected(0, true);

// put focus on the listbox
lbxItems.Focus();

//then send Shift/End (+ {END}) to SendKeys.SendWait
SendKeys.SendWait("+{END}");

// restore the view (scroll position)
lbxItems.TopIndex = iTopIndex;

结果:这将在几毫秒内选择10,000个项目。就像我实际使用键盘一样

答案 3 :(得分:0)

答案 4 :(得分:0)

找到了另一种方式,那就是更快&#34;:

[DllImport("user32.dll", EntryPoint = "SendMessage")]
internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);

// Select All
SendMessage(listBox.Handle, 0x185, (IntPtr)1, (IntPtr)(-1));

// Unselect All
SendMessage(listBox.Handle, 0x185, (IntPtr)0, (IntPtr)(-1));
相关问题