0

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.

2
  • Nobody knows what ListBox class you are talking about. Iterate the Items collection and use the item's Selected property. Find sample code in the MSDN Library article for ListBox.SelectionMode Commented Nov 6, 2012 at 13:54
  • Please look ListBox.GetSelectedIndices Commented Nov 6, 2012 at 14:08

4 Answers 4

4

Use the GetSelectedIndices() method.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Try this method

ListBox.SelectedIndexCollection SelectedIndices { get; }

SelectedIndex method is used when you allow to select only one value.

1 Comment

In Webforms, its not this property but the GetSelectedIndices() method.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.