Adding Design-Time support to your classes

If you use VS.NET you know that there are a number of classes that offer visual design-time support, i.e. they can be dragged and dropped on your form, and their properties can be set through the Properties Window. This saves you from writing the instance declaration and the code to set the variables. Some of such classes are EventLog, Timer, and many of the ADO.NET classes, such as SqlCommand, SqlConnection etc. This functionality is actually quite handy, and the good news is that you can add design-time support to your own classes as well! What you have to do is extremely simple–just take the following steps:

  1. Write your class as usual.
  2. Make the class inherit from System.ComponentModel.Component. This is actually the most important step: the Component class implements the IComponent interface, which marks the class as a special class with design-time support. The Component class also implements IDisposable, which you should usually implement anyway, and inherits from MarshalByRefObject, that makes the class remotable (through a proxy, and by reference).
  3. Compile the assembly (typically a Class Library).
  4. From the Windows Forms/ASP.NET project reference the library assembly, through the Add Reference… dialog.
  5. At this point you can use the class as usual, but to have it available from the Toolbox you have to right-click on the Component or another tab in the Toolbox, and add another reference to the class library assembly. (This time, this is done to have the class — or, to put it better, the component — added to the toolbox, in the step above you add a reference for the compilation instead).
  6. You’re done. You can now drag and drop the component on your form, and its icon will be added to the component tray below the form, so that you can select it and set the component’s properties from the Properties Window.

As a last note, I suggest you to use the Description attribute for most/all the component’s public properties, so that a description will be shown at the bottom of the Properties window when you select one of them. Other attributes such as Browsable and Category are also used as you would in custom control classes.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: