Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text of selected items in a ListBox

Tags:

c#

winforms

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

like image 770
ميداني حر Avatar asked Nov 28 '12 20:11

ميداني حر


People also ask

How do you retrieve the selected item in a ListBox?

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.

Which function is used to fetch a value based on the number returned by a ListBox control?

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.

How do I remove items from ListBox?

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.


2 Answers

You can iterate through your items like so:

        foreach (var item in listBox1.SelectedItems)
        {
            MessageBox.Show(item.ToString());
        }
like image 180
Jaime Torres Avatar answered Oct 11 '22 00:10

Jaime Torres


Try this solution:

string  item = "";    
foreach (int i in listBox1.SelectedIndices )
    {
       item += listBox1.Items[i] + Environment.NewLine;
    }
MessageBox.Show(item);
like image 41
Kirill Kryazhnikov Avatar answered Oct 11 '22 00:10

Kirill Kryazhnikov