1
votes

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?

1
Use SelectedItem = eCharlieface
My, is it that simple!Harald Coppoolse

1 Answers

1
votes

CharlieFace came up with the following solution, and it worked:

private MyEnum SelectedEnum
{
    get => (MyEnum)this.comboBox1.SelectedItem;
    set => this.comboBox1.SelectedItem = value;
}

In my example of a ComboBox that displays the Ids of Items:

private Item SelectedItem
{
    get => (Item)this.comboBox1.SelectedItem;
    set => this.comboBox1.SelectedItem = value;
}

So even though only the Name of the item is shown; SelectedItem contains the complete Item of the DataSource.

Thanks CharlieFace!