Get the text of selected items in a ListBox

I am trying to show the selected listBox1 items in the message box here is 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 in the message box, the frist I selected is displayed and the EX message is repeated: if I select 3 items, the message will appear 3 times with the first item

+6
source share
4 answers

i in the foreach loop has the index you need. You are using listBox1.SelectedIndex , which has only the first one. Thus, the element should be:

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

You can iterate through your elements as follows:

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

How about 1 message box with all items selected?

 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 is selected, this should give you a line for each selected item in your message box. There is probably a more convenient way to do this with linq, but you did not specify a .NET version.

+4
source

Try this solution:

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

All Articles