简体   繁体   中英

getting selected index of listbox(c#)

I have a ListBox with SelectionMode set to multiple. When I check the selected index using ListBox1.SelectedIndex I always get -1 even if I click on a item?? 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. 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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