How to create a drop down menu in WinForms and C#
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.
You need to set a datasource for your Combobox, it's better if you create a class and pass a list of Objects, for example:
private void Init()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Text = "displayText1", Value = "ValueText1" });
items.Add(new Item() { Text = "displayText2", Value = "ValueText2" });
items.Add(new Item() { Text = "displayText3", Value = "ValueText3" });
comboBox1.DataSource = items;
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";
}
public class Item
{
public Item() { }
public string Value { set; get; }
public string Text { set; get; }
}
Put the Init()
method in your FormName_Load(object sender, EventArgs e){}
.
It seems like the value is just a reference to what item is selected, correct? Then you can use the index of the combobox, makes it a lot easier.
Not sure if your items are known before build, if yes, then just add them in the designer, properties of the combobox. If not, then you can add them dynamically by just doing:
List<string> items = new List<string>() { "item1", "item2" };
comboBox1.DataSource = items;
And to know what item is selected:
int index = comboBox1.SelectedIndex;