简体   繁体   English

获取列表框的选定索引(C#)

[英]getting selected index of listbox(c#)

I have a ListBox with SelectionMode set to multiple. 我有一个SelectionBox设置为多个的ListBox When I check the selected index using ListBox1.SelectedIndex I always get -1 even if I click on a item?? 当我使用ListBox1.SelectedIndex检查所选索引时,即使单击某个项目,我也总是得到-1? I would like to be able to get index of multiple selected items in the listbox. 我希望能够获得列表框中多个选定项目的索引。

使用GetSelectedIndices()方法。

Since there can be more than one item selected you have to get the collection of SelectedItems. 由于可以选择一个以上的项目,因此必须获得SelectedItems的集合。 Loop through them. 遍历它们。 Each item has Index property. 每个项目都有索引属性。

Try this method 试试这个方法

ListBox.SelectedIndexCollection SelectedIndices { get; }

SelectedIndex method is used when you allow to select only one value. 当您只允许选择一个值时,将使用SelectedIndex方法。

Try something like this. 尝试这样的事情。 You will get all selected indexes in one string with this code. 使用此代码,您将在一个字符串中获得所有选定的索引。

int length = this.ListBox1.Items.Count;
    StringBuilder b = new StringBuilder();
    for ( int i = 0 ; i < length; i++ )
         {
      if ( this.ListBox1.Items[ i ] != null && this.ListBox1.Items[ i ].Selected ) 
              {
        b.Append( this.ListBox1.Items[ i ].Selected );
        b.Append( "," );
          }
     }
    if ( b.Length > 0 ) 
        {
      b.Length = b.Length - 1;
    }
    return b.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM