Recently someone expressed confusion as to the purpose of extending an existing control. Hence, I developed this example in order to show how extending an existing control is a quick process and can save you a lot of time on future projects.

The Basics

For the purposes of this example I picked a custom ComboBox. I find that I use ComboBoxes a lot in order to display an Enumerated Type for the user to choose a value from. Recently I wrote some sample code for interacting with a serial port. Of all the settings that the user had to select, three of them were enum types. Since I wanted to reuse the same type of ComboBox for multiple different Types I created a base class called EnumComboBox<T> where T should be an enum that can be displayed to the user.

When inheriting from existing control never subscribe to an event from the Base class (in this case the combo box), instead override the appropriate method (usually the same name as the event but starts with the prefix On, e.g.. Method for the event Click is OnClick).

I also make it a point to add the functional part of the code in an if block that checks to make sure we’re not in design mode. I have frequently experienced unexpected behaviour in design time as a result of overriding certain methods. In the example below if the if statement on line 7 is removed you’ll find that at run time each choice in the ComboBox drop down is listed twice.

In the example below (lines 9 – 14) the enum type is iterated and each value is entered into the Combo box (line 12), finally the first value of the Enum is selected as a default (line 14).

On lines 20,21,22 are examples of how to implement the class. If you copy this code into a project and build it you will find that the last three class are added to your toolbox as controls. Simply drag them onto your form and in a few lines of code we’ve create three controls that are easy to use and highly portable. 

Example Code

   1:   public abstract class EnumComboBox<T> : ComboBox
   2:      {
   4:          protected override void OnCreateControl()
   5:          {
   6:              Type enumType = typeof(T);
   7:              if (!this.DesignMode)
   8:              {
   9:                  base.Items.Clear();
  10:                  foreach (var item in Enum.GetValues(enumType))
  11:                  {
  12:                      base.Items.Add(item);
  13:                  }
  14:                  this.SelectedIndex = 0;
  15:              }
  16:              base.OnCreateControl();
  17:          }
  19:      }
  20:      public class ParityComboBox : EnumComboBox<Parity> { }
  21:      public class StopBitsComboBox : EnumComboBox<StopBits> { }
  22:      public class HandShakeComboBox : EnumComboBox<Handshake> { } 


The sample that I wrote that used the above code is here.

MSDN Entry on ComboBox

MSDN Entry on Enum