通过代码选择多个列表框项 [英] Selecting multiple Listbox items through code

查看:194
本文介绍了通过代码选择多个列表框项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经搜索了一段时间,似乎无法找到解决问题的方法,我尝试了多种方法来通过代码在列表框中选择多个项目,但是没有一个起作用,我得到的最好结果是我的列表框中有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);

           }
 }

因此,如您所见,我正试图告诉程序循环遍历列表框中的所有项目,并为每个等于搜索字符串"的项目获取索引并将其设置为选定状态.

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.

但是,所有这些代码所做的只是选择列表中等于搜索字符串"的第一项使其选中并停止,它不会遍历所有搜索字符串"项.

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设置为MulitSimpleMultiExpanded,但是您还需要使用forwhile循环而不是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;

这篇关于通过代码选择多个列表框项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆