Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

c# - ComboBox datasource: show complete item

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...