简体   繁体   English

在组合框中按对象值查找项目

[英]Finding an item by object value in Combobox

I have a combo box that is populated with an Arraylist, like below. 我有一个用Arraylist填充的组合框,如下所示。 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应该实现iComparable吗?

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

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

You shouldn't need to implement IComparable for IndexOf , just Equals . 您不需要为IndexOf实现IComparable ,只需实现Equals Otherwise it will default to Object.Equals , which only matches if the two references are to the same instance. 否则,它将默认为Object.Equals ,仅当两个引用都指向同一实例时才匹配。 (Not sure if this is a problem or not without seeing the definition of MakeEntity .) (在不查看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 文档: http : //msdn.microsoft.com/zh-cn/library/system.windows.forms.combobox.selecteditem.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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