listbox selected items in winform

2019-01-15 16:57发布

问题:

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

回答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;


回答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();


回答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.



回答4:

Actrually, if you know the type of object you input into ListBox, the selected item is that type, here is a sample: Input List of FileInfo to ListBox:

        FileInfo[] lFInfo = new DirectoryInfo(textBox1.Text).GetFiles();
        foreach (var i in lFInfo)
            lstFile.Items.Add(i);

A copy function to copy the selected files to path of textBox2.Text:

private void btnCopy_Click(object sender, EventArgs e)
 {
      foreach (FileInfo i in lstFile.SelectedItems)
          File.Copy(i.FullName, Path.Combine(textBox2.Text, i.Name));
  }


回答5:

ListBox.SelectedItems: Returns a collection of the currently selected items.

Loop through the SelectedItems collection of the listbox.

foreach (ListItem liItem in ListBox1.SelectedItems)
{
    // write your code.   
}