简体   繁体   中英

Winform Combobox with DataSource as List<int>

This may be a very simple question but I realized I could not get it work.

I have a Winform combo box with datasource as a List<int>

combo.DataSource = intList;

What do I put for .DisplayMember and .ValueMember in order to simply have a list of integer values? Not setting them will display nothing.

I have worked with other List<myObj> in which DisplayMember and ValueMember are myObj's properties. How about simple data type like int , string ?

When retrieving the selected item, one could simply cast (int)(combo.SelectedItem) or have to go through the property corresponding to ValueMember ?

The problem does not occur because you have a list of integers, it probably occurs because you add items to the list after assigning it to the .DataSource property. List does not have a mechanism to notify its container when items are added to or removed from it.

Either add items to the list before assigning it to the .DataSource property, or use a wrapper like BindingSource as Krishnraj Rana suggested.

Here BindingSource comes into picture. You can use it like this.

BindingSource bSource = new BindingSource();
bSource.DataSource = new List<int> { 1, 2, 3 };
combo.DataSource = bSource;

Though you can set datasource of combobox directly with list. like this -

combo.DataSource = intList;

This also works perfectly fine.

You can add items from list using foreach like this.

foreach (var v in intList)
{
   comboBox1.Items.Add(v.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM