C# 通过代码选择多个Listbox项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13130788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting multiple Listbox items through code
提问by user1784219
Hi there I have searched for a while now and can't seem to find a solution to my problem, I have tried multiple methods to select multiple items in my listbox through code however none have worked, The best result I got was 1 selected item in my listbox.
嗨,我已经搜索了一段时间,似乎找不到解决我的问题的方法,我尝试了多种方法通过代码在列表框中选择多个项目,但没有一个奏效,我得到的最佳结果是 1 个选定的项目在我的列表框中。
Basically I want to select multiple items of the same value.
基本上我想选择多个相同值的项目。
below is my code, sorry if I seem newbie but I am new to programming and still learning basic stuff.
下面是我的代码,对不起,如果我看起来是新手,但我是编程新手,仍在学习基本知识。
foreach (string p in listBox1.Items)
{
if (p == searchstring)
{
index = listBox1.Items.IndexOf(p);
listBox1.SetSelected(index,true);
}
}
So as you can see I am trying to tell the program to loop through all the items in my listbox, and for every item that equals "searchstring" get the index and set it as selected.
因此,正如您所看到的,我试图告诉程序循环遍历列表框中的所有项目,并为每个等于“searchstring”的项目获取索引并将其设置为选中状态。
However all this code does is select the first item in the list that equals "searchstring" makes it selected and stops, it doesn't iterate through all the "searchstring" items.
然而,这段代码所做的只是选择列表中第一个等于“searchstring”的项目,使其被选中并停止,它不会遍历所有“searchstring”项目。
回答by Nikola Davidovic
As suggested in the comment, you should set SelectionModeto either MulitSimpleor MultiExpandeddepending on your needs, but you also need to use foror whileloop instead offoreach, because foreachloop doesn't allow the collection to be changed during iterations. Therefore, even setting this Property won't make your code run and you will get the exception. Try this:
正如评论中所建议的,您应该根据需要设置SelectionMode为MulitSimple或MultiExpanded,但您还需要使用for或while循环而不是foreach,因为foreach循环不允许在迭代期间更改集合。因此,即使设置此属性也不会使您的代码运行,并且您将收到异常。尝试这个:
for(int i = 0; i<listBox1.Items.Count;i++)
{
string p = listBox1.Items[i].ToString();
if (p == searchstring)
{
listBox1.SetSelected(i, true);
}
}
You can set SelectionMode either in the Properties window when using designer or in, for instance, constructor of your Formusing this code:
您可以在使用设计器时在“属性”窗口中设置 SelectionMode,也可以在Form使用以下代码的构造函数中设置 SelectionMode :
listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;

