Suppose you have a fairly small sequence of Items where every Item has properties: Id and Name.
Id and Name are unique.
You want to show the items in a ListControl like a combo box.
You only want to show the Name of the Item, not the Id.
When the name of a displayed Item is selected, you want the Id of the Item as Selected Value:
This is easily done using a DataSource by setting properties DisplayMember and ValueMember
IList<Item> items = ...
this.ComboBox1.DataSource = items;
this.ComboBox1.DisplayMember = nameof(Item.Name);
this.ComboBox1.ValueMember = nameof(Item.Id)
When the item is selected:
int selectedId = (int) this.ComboBox1.SelectedValue;
And you can select an item by Id:
Item item = ...
this.ComboBox.SelectedValue = item.Id;
And presto, the name of the item is shown.
But now I have a sequence of items without properties, for instance an Enum:
IList<MyEnum> enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList();
this.comboBox1.DataSource = enums;
This is enough to display the enums in the combo box. No need to set DisplayMember / ValueMember. I can get the selected enum:
MyEnum e = (MyEnum)this.ComboBox1.SelectedValue;
But I can't set it:
MyEnum e = ...
this.ComboBox1.SelectedValue = e;
Leads to exception: System.InvalidOperationException: 'Cannot set the SelectedValue in a ListControl with an empty ValueMember.'
So what should I set in ValueMember?
SelectedItem = e
– Charlieface