Selecting multiple Listbox items through code(通过代码选择多个Listbox项)
问题描述
您好,我已经搜索了一段时间,但似乎找不到解决问题的方法,我尝试了多种方法来通过代码选择列表框中的多个项目,但是没有一个有效,我得到的最好结果是在我的列表框中选择了 1 个项目.
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.
基本上我想选择多个相同值的项目.
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);
}
}
如您所见,我试图告诉程序循环遍历列表框中的所有项目,并为每个等于searchstring"的项目获取索引并将其设置为选中.
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"的第一个项目使其被选中并停止,它不会遍历所有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.
推荐答案
按照评论中的建议,您应该将 SelectionMode
设置为 MulitSimple
或 MultiExpanded
取决于你的需要,但你也需要使用 for
或 while
循环而不是 foreach
,因为 foreach
循环不允许在迭代期间更改集合.因此,即使设置此属性也不会使您的代码运行,您将获得异常.试试这个:
As suggested in the comment, you should set SelectionMode
to either MulitSimple
or MultiExpanded
depending on your needs, but you also need to use for
or while
loop instead offoreach
, because foreach
loop 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:
for(int i = 0; i<listBox1.Items.Count;i++)
{
string p = listBox1.Items[i].ToString();
if (p == searchstring)
{
listBox1.SetSelected(i, true);
}
}
您可以在使用设计器时在属性"窗口中设置 SelectionMode,也可以在 Form
的构造函数中使用以下代码:
You can set SelectionMode either in the Properties window when using designer or in, for instance, constructor of your Form
using this code:
listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
这篇关于通过代码选择多个Listbox项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过代码选择多个Listbox项
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01