Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何快速选择列表框中的所有项目?_C#_Winforms_Listbox - Fatal编程技术网

C# 如何快速选择列表框中的所有项目?

C# 如何快速选择列表框中的所有项目?,c#,winforms,listbox,C#,Winforms,Listbox,我在绑定到数据源(BindingList)的窗体(Windows窗体)上有一个ownerdrawn列表框。 我需要提供一个选项来选择所有项目(高达500000)非常快 这就是我目前正在做的: for (int i = 0; i < listBox.Items.Count; i++) listBox.SetSelected(i, true); for(int i=0;i

我在绑定到数据源(BindingList)的窗体(Windows窗体)上有一个ownerdrawn列表框。 我需要提供一个选项来选择所有项目(高达500000)非常快

这就是我目前正在做的:

for (int i = 0; i < listBox.Items.Count; i++)
    listBox.SetSelected(i, true);
for(int i=0;i
这是令人难以置信的缓慢和不可接受的。有人知道更好的解决方案吗?

您可以使用SelectAll()方法

Listbox.SelectAll()


您可以尝试listbox.SelectAll()

以下是ListBox SelectAll()上的microsoft文档链接:


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

listBox.BeginUpdate();

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

listBox.EndUpdate();
listBox.BeginUpdate();
对于(int i=0;i
找到了另一种方法,即“更快”:


我找不到一种速度快到可以接受的方法。 我尝试了BeginUpdate/EndUpdate,这很有帮助,但在intel core i5笔记本电脑上仍然需要4.3秒。 因此,这是相当蹩脚的,但它可以工作-至少在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;

结果:这将在几毫秒内选择10000项。和它一样,我实际上使用了键盘

更好地减少了项目的数量。很长时间没有使用表单了。您是否能够执行类似于
listBox.SelectedItems=listBox.Items的操作?对于
选择的索引
?@Steve:Nice try;)不,这不是选项。离题,但我不认为包含500000项的列表框如何可用。您可能想查看您的设计。@Rob:不,SelectedItems是get only。@MauriceStam的建议加上这可能是最好的解决方案(不确定SelectAll是否在内部禁用绘图),这取决于他使用的是WPF还是Windows窗体。WF没有用于WPF的
SelectAll
方法。提问者正在使用Windows窗体(因为WPF没有
SetSelected()
)。是的,Windows窗体,对不起;)哦,好的,对不起。你可以这样做,让它稍微快一点。a=Listbox.Items.Count;并使用一个循环。完美!这要快得多。@Maertin-Seequestion@Norman我已经在示例中添加了代码。最好不要在问题中重复解决方案。投票制度应该把最好的解决方案放在首位。社区可能仍然认为另一种解决方案会更好!这适用于WPF,而不是Windows窗体。这不会更新SelectedItems或SelectedDices。@TonyEdgecombe,从问题中可以看出,这不是一个要求。
//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;