C# – How to create a derived ComboBox with pre-bound datasource that is designer friendly


I'd like to create a derived control from System.Windows.Forms.ComboBox that is bound to a list of objects that I retrieve from the database. Idea is other developers can just drop this control on their form without having to worry about the datasource, binding, unless they want to.

I have tried to extend combobox and then set the DataSource, DisplayMember, and ValueMember in the constructor.

public class CustomComboBox : ComboBox
    public CustomComboBox() 
        this.DataSource = MyDAL.GetItems(); // Returns List<MyItem>
        this.DisplayMember = "Name";
        this.ValueMember = "ItemID";

Works when I run, but throws a lot of errors in Visual Studio's once it's added to any form. The error I get is:

"Code generation for property 'Items' failed. Error was: 'Object reference not set to an instance of an object"

What's the correct way to accomplish this (C#, Winforms, .NET 2.0+)?

Best Solution

The problem is that the designer actually does some compilation and execution in a slightly different context than normally running the program does.

In the constructor, you can wrap your code in:

if (!DesignMode)
  //Do this stuff

That will tell the designer to not run any of your initialization code while it is being designed.

Related Question