Displaying selected items of listbox into a message box
10,575
Solution 1
You can create temporary variable to save text in it and then create a messagebox.
StringBuilder message = new StringBuilder();
foreach (object selectedItem in listBox1.SelectedItems)
{
message.AppendLine(selectedItem.ToString());
}
MessageBox.Show(message.ToString());
Solution 2
You can create a single string based on all the SelectedItems
and then display that in the MessageBox. Like
string str = string.Join(",",
listBox1.SelectedItems.Cast<object>().Select(r => r.ToString()));
MessageBox.Show(str);
Comments
-
ankita alung almost 2 years
I am able to display multiple selected items from a listbox into a text box on a button click but how can I display the same on a message box? I mean displaying first item on a messagebox is not an issue but multiple items at once is. Suggestions please...
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace cities { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { textBox1.Clear(); foreach (object selectedItem in listBox1.SelectedItems) { textBox1.AppendText(selectedItem.ToString() + Environment.NewLine); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
-
Sayse about 11 yearsI think if theres too many selected items then the ok button and possibly top bar will go off the screen :)
-
ankita alung about 11 yearsReally nice solution! Thanks!