A.D.
A.D.

Reputation: 1116

Setting ComboBox SelectedValue

My Winform ComboBox is bound this way:

this.myComboBox.DataSource = myDS;
this.myComboBox.DisplayMember = PropertyHelper<MyType>.NameOf(i => i.prop1);
this.myComboBox.ValueMember = PropertyHelper<MyType>.NameOf(i => i.prop2);

myDS does include a MyType element whose prop2 value = myType.prop2val.

I am trying to set the Combobox item with this item. 1st attempt:

myComboBox.SelectedValue = (int)myType.prop2val;

This does not work : it sets myComboBox.SelectedValue and SelectedItem to null.

2nd attempt:

myComboBox.SelectedItem = ((List<MyType>)myComboBox.DataSource)
                         .FirstOrDefault(a => a.prop2 == myType.prop2val);

This line works but I find it ugly.

I am pretty sure that I missed something to make the first attempt work. Any help appreciated.

Upvotes: 0

Views: 1179

Answers (1)

Fabio
Fabio

Reputation: 32445

Most obviously reason for your problem is that type of myType.prop2 and type of value given in myComboBox.SelectedValue are different types.

As you said in the comments type of MyType.prop2 is long, but for SelectedValue you cast value to int.

myComboBox.SelectedValue = (int)myType.prop2val;

I didn't understand why you need to cast it to int, but anyway types for property in ValueMember and type for SelectedValue should be same to satisfy equality.

ComboBox compares values as values of type object, so boxed value of type long will not be equal to boxed value of type int.
ComboBox comparison code looks something like below

int givenSelectedValue = 2;

object selectedValue = givenSelectedValue;  // boxed to object type
for (int i = 0; i < internalDataSourceList.Count; i++) 
{
    object itemValue = // get value of list[i] and property from ValueMember
    if (selectedValue.Equals(itemValue)) 
    {
        return i; // Return index of selected item
    }
}

// if not found
return -1;

Upvotes: 1

Related Questions