Value added twice during WinForms construction
I have the following code in VS2010 Ultimate:
class MyComboBox : System.Windows.Forms.ComboBox
{
开发者_开发百科 public MyComboBox() {
this.Items.Add("myValue");
this.Items.Add("myValue2");
this.Items.Add("myValue3");
this.Items.Add("myValueN");
}
// ...
}
When I run the example WinForms application, every instance of the control has "myValue" twice in the dropdown list (first and last). Why does this happen, and how do I fix it?
This happens because the constructor also gets executed at design time. So as soon as you drop your custom combobox on a form, it immediately gets filled with 4 values. Which then get persisted in the form's InitializeComponent() method. When you next run your form, your constructor gets executed again, adding 4 values to the combobox, then InitializeComponent adds 4 more.
Several ways to fix this but the clean ones are fairly painful. By far the simplest way is to delay adding these items until you can test the DesignTime property:
class MyComboBox : ComboBox {
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (this.Items.Count == 0) {
this.Items.Add("myValue");
this.Items.Add("myValue2");
this.Items.Add("myValue3");
this.Items.Add("myValueN");
}
}
}
If not being able to edit the items in the dropdown is okay then this is the best fix:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public new ObjectCollection Items {
get { return base.Items; }
}
精彩评论