Next, if you load in the list of Items
, objects of type A, you can only use in the SelectedItem
property objects that compare with this type.
The following example does not work because of this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class MyClass
{
private string p;
public MyClass(string p) { this.p = p; }
public override string ToString() { return this.p; }
}
private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.Items.AddRange(new[]
{
new MyClass("RJ"),
new MyClass("MG"),
new MyClass("SP"),
});
this.comboBox1.SelectedItem = "SP"; // tipo string não se compara com tipo MyClass
}
}
On the other hand, if I insert strings in the list of items, yes, I can use the SelectedItem property with a string, since two strings compare themselves:
this.comboBox1.Items.AddRange(new[]
{
"RJ",
"MG",
"SP",
});
this.comboBox1.SelectedItem = "SP";