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);
Share:
10,575
ankita alung
Author by

ankita alung

Hi!

Updated on June 13, 2022

Comments

  • ankita alung
    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
    Sayse about 11 years
    I think if theres too many selected items then the ok button and possibly top bar will go off the screen :)
  • ankita alung
    ankita alung about 11 years
    Really nice solution! Thanks!