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:
If not being able to edit the items in the dropdown is okay then this is the best fix: