user3726459 user3726459 - 4 months ago 30
C# Question

How do I access Combobox item MemberValue in windows forms?

I am trying to access a combobox item's value. The item's value is of type MyClass

List<MyClass> myIitemsList = getMyClassItemsMethod();
if (myIitemsList .Count > 0)
for (int i = 0; i < myIitemsList .Count; i++)
List<MyClass> selectedMyClassItems = myIitemsList .FindAll(x => x.myClassNumber == i);
string itemtext = "MyClass " + i ;
myComboBox.Items.Add(new { itemtext, ValueMember = selectedMyClassItems});

here is my sample code. Now i am trying to access the ValueMember. When I select an item in the combobox, I am able to get the selected item.

var ddlMyClassSelectedItem = myComboBox.SelectedItem;

In the Debug Watch windo, I am able to see that the ValueMember for the item has the items as a list, but I don't know how to access/retrieve them.


Lets discuss what you've done. How you retrieve your members is of little interest, although you could do it this way

myComboBox.DisplayMemeber = "Display";
myComboBox.ValueMemeber = "Value";
myComboBox.DataSource = 
    getMyClassItemsMethod().OrderBy(c => c.myClassNumber).
    Select(c => new { Display = "Memeber: " + c.myClassNumber, Value = c}).ToList();

It will work and now you have selected an item using myComboBox.SelectedItem. But you running into a problem that your item is in fact an anonymous type and you can't cast it easily.

On this note, why don't you declare a type like

class ComboItem
    public string Display {get; set;}        
    public MyClass Value {get; set;}

And use this type instead of anonymous type. i.e. instead of new {...} you do new ComboItem {...}. Now, this is easy

var ddlMyClassSelectedItem = (ComboItem)myComboBox.SelectedItem;

Now you know that ddlMyClassSelectedItem is of ComboItem type