listbox selected items in winform

22,197

Solution 1

You could do something like:

string text = "";

foreach (System.Data.DataRowView item in listBox1.SelectedItems) {
    text += item.Row.Field<String>(0) + ", ";
}
textBox1.Text = text;

Solution 2

You need to iterate over the collection of items. Something like:

textBox1.Text = "";
foreach (object o in listBox1.SelectedItems)
   textBox1.Text += (textBox1.Text == "" ? "" :", ") + o.ToString();

Solution 3

The post is quite old but lacks a correct general answer which can work regardless of the data-bound item type for example for List<T>, DataTable, or can work regardless of setting or not setting DisplayMember.

The correct way to get text of an item in a ListBox or a ComboBox is using GetItemText method.

It doesn't matter what is the type of item, if you have used DataSource and DisplayMember it uses DisplayMember to return text, otherwise it uses ToString method of item.

For example, to get a comma-separated list of selected item texts:

var texts = this.listBox1.SelectedItems.Cast<object>()
                .Select(x => this.listBox1.GetItemText(x));

MessageBox.Show(string.Join(",", texts));

Note: For those who are looking for selected item values rather that selected item texts regardless of the item type and the value member field, they use GetItemValue extension method.

Share:
22,197
Surya sasidhar
Author by

Surya sasidhar

Hi, my name is surya sasidhar, dot net developer. I completed my MBA . I Love two things one my darling Daughter Khushi Datha and another doing programming. i have to achieve a lot in dot net programming.

Updated on July 21, 2022

Comments

  • Surya sasidhar
    Surya sasidhar almost 2 years

    I have listbox, button, and textbox controls in a Windows application. How can I display multiple selected values in a textbox.

    this is my code

    textBox1.Text = listBox1.SelectedItems.ToString();
    

    but it display in textbox like this: (I select more than one item)

    System.Windows.Forms.ListBox+Selec. 
    

    please help me