Why in C# , in the control combobox , i can't change the property SelectedItem?
I have a simple class called Tuple. whi开发者_运维知识库ch looks like this :
class tuple
{
string name;
string code
}
i inserted few of these items into a combobox, now when i want to select through the code some item, i try to write
myComboBox.selectedItem = new tuple("Hello" , "5");
and of course it doesn't work at all and the selected item doesn't change.
let's assume the items list of the combobox contains an item that looks like this, how can he compare the items ?
i inherited iComparable and implemented it, but unfortunately he doesn't use it at all..
how can i set the selected item ? should i run an all the items with a loop and compare them by myself ?
thanks
You'll need to override the Equals
method in order to provide a custom comparison that is able to assert if two tuple
instance represent the same value.
You should also check the following MSDN entries about how to properly override the Equals
method:
Implementing the Equals Method
Guidelines for Implementing Equals and the Equality Operator (==)
Microsoft Code Analysis Rule about overriding GetHashCode
whenever you override Equals
:
CA2218: Override GetHashCode on overriding Equals
The value assigned to SelectedItem
must be one of the items that already exists in the combo box data source. From the MSDN documentation (emphasis mine):
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.
By using:
myComboBox.SelectedItem = new tuple("Hello" , "5");
you are attempting to assign it a new instance of a tuple, that can't possibly be in the associated data source.
The correct implementation would be to find the existing item in the data source (by whatever criteria is appropriate to define a match) and assign that to SelectedItem
. LINQ can make this quite easy:
myComboBox.SelectedItem =
myComboBox.Items.OfType<tuple>()
.Where( t => t.name == "Hello" && t.code == 5 )
.FirstOrDefault();
Also, if you're using .NET 4.0, you don't have to implement your own tuple class, there's a new generic implementation Tuple<T1,T2>
which already has structural equality semantics built into it.
精彩评论