RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


.NET Building Blocks: Custom User Control Fundamentals

Find out the gritty details required to create, test, use, inherit, install, and distribute .NET User Controls of all types.

ith the .NET framework, you can build Windows Forms applications (those that run on your local machine) or Web Form applications (those that run in your browser). A Windows Form is simply a container for a collection of controls—buttons, fields, drop-down boxes, selectors, and so forth—that users may interact with and manipulate. This article discusses the fundamentals of such controls, including both how to consume them at design time and, in particular, how to create your own custom controls. It is not nearly as daunting as you might think at first glance to create custom controls; after you learn the principles laid out here, you will be able to make your own library of building blocks, adding your controls to the Visual Studio Toolbox right alongside the standard ones.

What You'll Cover
  • Types of custom controls. You will learn about the different types, when to use them, and how to create them.
  • Testing custom controls. Visual Studio provides a runnable wrapper—a remarkable tool called the "UserControl Test Container."
  • Incorporating custom controls into your applications. Understand the logistics of control libraries, loading them into your Toolbox, and manipulating them.
  • Augmenting custom controls. With some handy tips you can integrate your controls seamlessly into Visual Studio.
What You Need
  • Visual Studio 2008 or VS2005
  • C# 3.0 or 2.0 (there are a couple of spots you'll need to adjust if using C# 2.0 in VS2005)
  • .NET Framework: 2.0 or higher

A Simple Composite User Control
In this first exercise, you will build "ClockControl," a simple digital-clock timer control. The basic example comes from the MSDN documentation "Walkthrough: Authoring a Composite Control with Visual C#," because it serves as a good launching point for further discussion. The MSDN walkthrough provides step-by-step instructions to create this user control, and is a useful aid if you don't have much experience with controls, so I won't duplicate those instructions here. The version of the example you'll see here deviates from the walkthrough both in component naming and in coding; it's simpler and easier to comprehend. Also, rather than having to build the example, you can download the finished code, which you can then load and run immediately.

If you do want to build it yourself, here's a brief version of the entire procedure:

  1. Start a new project of type Windows Forms Control Library. When compiled, this will result in a DLL (library) file instead of an executable.
  2. Visual Studio automatically adds a single user control, represented by UserControl1.cs and its associated designer files. Rename the UserControl1.cs file in Solution Explorer to ClockControl.cs. Visual Studio will ask if you want to rename associated objects when you do this; answer "Yes".
  3. Just as you would with a Windows Forms application, add a standard Label control and a Timer component to the designer surface.
  4. Set these important properties of the Timer component:
    • Because the clock displays at a resolution of one second, the timer activity should match: set the Interval property to 1000 (milliseconds).
    • Turn on the Timer component by setting the Enabled property to True.
The MSDN walkthrough gives the code in smaller chunks, but because it's such a short program, here's the whole thing:

   namespace ControlLib
      public partial class ClockControl : UserControl
        public ClockControl()
        public Color ClockForeColor
          get { return clockLabel.ForeColor; }
          set { clockLabel.ForeColor = value; }
        public Color ClockBackColor
          get { return clockLabel.BackColor; }
          set { clockLabel.BackColor = value; }
        protected virtual void timer1_Tick(object sender, EventArgs e)
          clockLabel.Text = DateTime.Now.ToLongTimeString();
Author's Note: I streamlined and shortened the code, and introduced a few minor stylistic changes that make it cleaner. These include:
  • Naming the control "ClockControl" instead of "ctlClock" to avoid abbreviations and to use the suffix to indicate what the type is—a control.
  • Naming the label "clockLabel" instead of "lblDisplay," signifying that the object is a Label and its purpose is to display the clock.
  • Eliminating redundant color capture in the foreground and background color properties, instead assigning and retrieving them directly from an embedded control.

Testing a Control
Figure 1. UserControl Test Container: Visual Studio lets you perform isolated "containerized" testing of your custom controls, in this case the ClockControl.
When you create a Windows Forms Application project and compile it, Visual Studio generates a binary executable file (named <projectName>.exe) that you can execute like any other Windows program. When you create a Windows Forms Control Library project and compile it, however, Visual Studio generates a dynamic linked library (DLL) file. DLLs are also binary files, but they're not stand-alone executables; they must be referenced by some executable file for the code in them to actually run. The seemingly natural way to test a control, then, is to create a sample Windows Forms application, place your control on the form, and then run the application. In fact, that is what you had to do in the ancient days of .NET 1.1 and earlier. Starting with .NET 2.0, however, Visual Studio has provided a UserControl Test Container that saves you all that work. Using it is as simple as running an application by pressing F5 or Ctrl-F5 in Visual Studio. When you do this inside a control library project, you launch the test container (see Figure 1). Observe that the clock updates every second with the current time, so the test container is truly running your control just as if it were in a Windows Forms application (which it is).

As you will observe from Figure 1, the UserControl Test Container provides quite a bit more than you would get if you just placed your control on a test form and ran it. First, it lets you select any user control in your current library from the drop-down control at the top of the form. Because there is only one user control in your library so far (ClockControl), it automatically selects that control and runs it. If you had more than one, you could invoke whichever one you wanted to test by selecting it and clicking the Load button.

The second major benefit of the UserControl Test Container is that it gives you access to all your control's public properties.

Some of those properties cannot meaningfully be changed in the test container, primarily those that describe the relationship between your control and its parent form. So you cannot, for example, change the Location property from its value of (0, 0). This rule does not entirely hold true, though, as you could change the Dock property value from None to Fill—and you would see the background of the control expand to fill the preview pane.

Figure 2. Property Editor: Activating the value field of a property automatically opens an appropriate property editor—in this case, a color picker palette.
Probably the most interesting properties are those your control explicitly exposes as public properties (ClockBackColor and ClockForeColor for the ClockControl). Assuming you have the properties grouped by category, by default your properties will be in the miscellaneous (Misc) category at the bottom of the list. Clicking in the property value for a color enables the field and exposes a dropdown button (see Figure 2). Opening the drop-down reveals a property editor for the property's type—a multi-tabbed color picker palette in this case. In Figure 2, you can see the colors selected for both the foreground and background, with the color palette exposed. Changes to these property values are reflected in the preview pane immediately.

Now that you've implemented and tested the ClockControl, you are free to use it like any standard .NET control. You need only load it into the Toolbox (which you will learn about shortly). Once in the Toolbox, you can drag it onto the designer surface just like any built-in control such as a Button or CheckBox. When you place a user control on your form, it behaves like any other standard control: selecting it in the designer shows its properties in the Properties window, where you can change the ClockBackColor or ClockForeColor or other standard properties. You could also place your user control into another user control (just as you placed a Label control into the ClockControl), or you can extend the control through inheritance, discussed next.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date