简体   繁体   中英

Finding an item by object value in Combobox

I have a combo box that is populated with an Arraylist, like below. If I have another instance of same object, how do I select that object in the combobox? Please look at the code below to understand.

        MakeEntity selectedMake = Make.GetMakeByTitle("Honda");
        List<MakeEntity> allMakes = Make.GetAllMakes();
        cbVehicleMake.DataSource = allMakes;
        cbVehicleMake.SelectedIndex = cbVehicleMake.Items.IndexOf(selectedMake);

But last line is not working as expected. Can I get it to run at all or am I going in the wrong direction? Should MakeEntity implement iComparable?

假设MakeEntity有一个名为id的属性!

 cbVehicleMake.SeletedItem=allMakes.Find(q=>q.Id==selectedMake.Id))

You shouldn't need to implement IComparable for IndexOf , just Equals . Otherwise it will default to Object.Equals , which only matches if the two references are to the same instance. (Not sure if this is a problem or not without seeing the definition of MakeEntity .)

Also, just use:

cbVehicleMake.SelectedItem = selectedMake;

This will internally handle finding the object in the options.

Documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM