If you want a value and a caption (label), create an appropriate class
class ComboItem
{
public int ID { get; set; }
public string Text { get; set; }
}
In the ComboBox you then set the DisplayMember
property to Text
and the ValueMember
property to ID
.
The DropDownStyle
of the ComboBox determines its behavior. DropDownStyle.DropDown
enables the user to type in text. With DropDownStyle.DropDownList
the user can only select items from the list.
You can fill the ComboBox
like this:
myCombo.DataSource = new ComboItem[] {
new ComboItem{ ID = 1, Text = "One" },
new ComboItem{ ID = 2, Text = "Two" },
new ComboItem{ ID = 3, Text = "Three" }
};
The DataSource
can be any kind of enumerable.
You can retrieve the selected ID like this
int id = (int)myComboBox.SelectedValue;
Note that you can add any type of item to the ComboBox. If you don't specify the DisplayMember
and ValueMember
properties, the ComboBox uses the ToString
method of the object to determine the text displayed and you can retrieve the selected item (not selected value) through the SelectedItem
property.
If you add objects of this type ...
class Person
{
public int PersonID { get; set }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return FirstName + " " + LastName;
}
}
...to the ComboBox, you can retrieve the selected item like this
Person selectedPerson = (Person)myComboBox.SelectedItem;
int personID = selectedPerson.PersonID;
The ComboBox will display the first and last names of the persons.