如何识别是否从 c# winforms 中的列表框控件中选择了多个索引?

how to identify if multiple indexes are selected from the listbox control in c# winforms?

我正在开发一个应用程序,我需要放置字段 在前端就像拿复选框一样。如果用户 select 在复选框上编辑了特定字段,那么基于 selection 我将从 sql 数据库生成 crystal 报告。

所以最多 10 个字段复选框就足够了。但是字段增加到 30 个,表单上的复选框数也增加了。

所以我决定采用列表框。但是在列表框中如何识别 select从用户那里编辑了多个项目?

在列表框中,我已将 SelectionMode 属性 设置为 MultiSimple

但是如果我 select 两个或更多项目,列表框只取第一个项目的索引。

代码:

if(listbox1.SelectedIndex==0)
{

 //my code for first field.
}

if(listbox1.SelectedIndex==1)
{

 //my code for second field.
}

注意:我写了一个方法来获取基于用户的动态 sql 查询 selected 项。所以在我的方法 createSQLquery() 中,我想确定 索引。

我想确定用户从前端 select 编辑了哪些项目,并基于此我将继续编写我的代码。

谢谢

您可以通过三种方式找到
1)

  foreach (object item in listbox.SelectedItems)
    {
        // do domething
    }

2)

 for (int i = 0; i < ListBox1.Items.Count; i++)
  {
     if (ListBox1.Items[i].Selected)
       {
           // do domething
        }
   }

3)

var selected = ListBox1.GetSelectedIndices().ToList();
var selectedValues = (from c in selected
                      select ListBox1.Items[c].Value).ToList();

您可以使用 ListBox.SelectedIndices 属性 获取多个选定项目的索引。

Gets a collection that contains the zero-based indexes of all currently selected items in the ListBox.