I'm trying to show the selected items of listBox1 in a Message Box here's the code:
int index;
string item;
foreach (int i in listBox1 .SelectedIndices )
{
index = listBox1.SelectedIndex;
item = listBox1.Items[index].ToString ();
groupids = item;
MessageBox.Show(groupids);
}
The problem is that when I select more than one item the message box shows the frist one I've selected and repeats the message EX: if I selected 3 items the message will appear 3 times with the first item
To retrieve a collection containing all selected items in a multiple-selection ListBox, use the SelectedItems property. If you want to obtain the index position of the currently selected item in the ListBox, use the SelectedIndex property.
ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method. Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item.
You can use this method to remove a specific item from the list by specifying the actual item to remove from the list. To specify the index of the item to remove instead of the item itself, use the RemoveAt method. To remove all items from the list, use the Clear method.
You can iterate through your items like so:
foreach (var item in listBox1.SelectedItems)
{
MessageBox.Show(item.ToString());
}
Try this solution:
string item = "";
foreach (int i in listBox1.SelectedIndices )
{
item += listBox1.Items[i] + Environment.NewLine;
}
MessageBox.Show(item);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With