Reputation: 16375
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.
Upvotes: 0
Views: 2606
Reputation: 575
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();
Upvotes: 0
Reputation: 29
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.
Upvotes: 2
Reputation: 12053
Try this method
ListBox.SelectedIndexCollection SelectedIndices { get; }
SelectedIndex method is used when you allow to select only one value.
Upvotes: 1