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.
-
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.SelectionModeHans Passant– Hans Passant2012-11-06 13:54:30 +00:00Commented Nov 6, 2012 at 13:54
-
Please look ListBox.GetSelectedIndiceshuMpty duMpty– huMpty duMpty2012-11-06 14:08:59 +00:00Commented Nov 6, 2012 at 14:08
Add a comment
|
4 Answers
Try this method
ListBox.SelectedIndexCollection SelectedIndices { get; }
SelectedIndex method is used when you allow to select only one value.
1 Comment
Rik
In Webforms, its not this property but the GetSelectedIndices() method.
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();