简体   繁体   中英

Get text of selected items in a ListBox

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

You can iterate through your items like so:

        foreach (var item in listBox1.SelectedItems)
        {
            MessageBox.Show(item.ToString());
        }

The i in the foreach loop has the index you need. You're using listBox1.SelectedIndex which only has the first one. So item should be:

item = listBox1.Items[i].ToString ();

How about 1 message box with all the selected items?

List<string> selectedList = new List<string>();
foreach (var item in listBox1.SelectedItems) {
   selectedList.Add(item.ToString());
}
if (selectedList.Count() == 0) { return; }
MessageBox.Show("Selected Items: " + Environment.NewLine +
        string.Join(Environment.NewLine, selectedList));

If any are selected, this should give you a line for each selected item in your message box. There's probably a prettier way to do this with linq but you didn't specify .NET version.

Try this solution:

string  item = "";    
foreach (int i in listBox1.SelectedIndices )
    {
       item += listBox1.Items[i] + Environment.NewLine;
    }
MessageBox.Show(item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM