Use data-binding, best feature Windows Forms come up with ;)
var list = new[]
{
new Team { Id = 1, Name = "One" },
new Team { Id = 2, Name = "Two" },
new Team { Id = 3, Name = "Three" }
};
combobox.ValueMember = "Id"; // Name of property to represent a Value
combobox.DisplayMember = "Name"; // Name of property to represent displayed text.
combobox.DataSource = list; // Bind all items to the control
Selections can be accessed by Selected..
properties of combobox.
var selectedTeamId = (int)combobox.SelectedValue;
var selectedTeamName = combobox.SelectedText;
var selectedTeam = (Team)combobox.SelectedItem;
Notice that SelectedValue
and SelectedItem
return object
type, so you need cast it to correct type before using.