Site Search

Lab 6: User-Defined Custom Controls

Learning Objectives for Lab 6

After completion of today's lab, you should be able to

Custom Controls

The .NET Framework allows the programmer to develop and implement new custom controls.

You are able to write custom controls that extend the functionality of existing controls through

Since controls in .NET are classes, creating custom controls is essentially declaring a new class that inherits from a System.Windows.Forms Control class.

Inheriting from a Windows Forms Control

You can derive an inherited control from any existing Windows Forms control. This approach allows you to retain all of the inherent functionality of a Windows Forms control, and to then extend that functionality by adding custom properties, methods, or other functionality.

For example, you might write a class named NumberTextBox derived from TextBox that only accepts numbers as input:

   using System;
   using System.Windows.Forms;

   public class NumberTextBox : TextBox
   {
      //Handle the Key Press event
      protected override void OnKeyPress(KeyPressEventArgs e)
      {
         //mark the KeyPress event as handled
         e.Handled = true;
         
         //get the key pressed by the user
         char key = e.KeyChar;
         
         //if the key pressed is a digit, allow it; otherwise ignore it
         if(Char.IsDigit(key))
            this.Text += key;
            
         //position the cursor at the end of the user input so far
         this.SelectionStart = this.Text.Length;
      }  
   } 

One could easily add more methods to the NumberTextBox class to extend its functionality.

Using a user-defined inherited control

As programmers, we can create inherited custom controls in Visual Studio.NET by writing adding new classes to a project that represent our custom controls, than instantiating objects of that new class and invoking its methods and properties.

   NumberTextBox myTextBox = new NumberTextBox();

   myTextBox.Location = new Point(50, 70);  //Set its properties
   myTextBox.Size = new Size(200, 20);
   myTextBox.Text = "";

   this.Controls.Add(myTextBox);

A cool feature with Visual Studio 2005 is that our new inherited control is placed in the ToolBox and we can drag-and-drop the inherited control onto a Form in design view just like the built-in controls.

Activity - Create an Inherited Control

Write a custom control derived from TextBox that allows only uppercase letters. If a letter is entered as lowercase, convert it to uppercase. Ignore any non-letters entered as input.

Activity 1 - Writing a AllCapsTextBox Class

  1. Create a New Project called WindowsUI in Solution Lab6
  2. Change the name of the Form1 file to MainForm.cs
  3. Change the text displayed in MainForm's title bar to Lab 6

  4. Use the Project menu to add a New Class to your project named AllCapsTextBox
  5. Write the OnKeyPress method to convert all letters entered to uppercase. Ignore non-letter input.
  6. Build your project and drag-and-drop a AllCapsTextBox onto your MainForm
  7. Test your custom control

Composite Controls: Controls that encapsulate other controls

Composite Control

Controls that encapsulate other controls are called composite controls and are derived from UserControl as their base class. By creating a composite control, the code can be reused in any number of different contexts.

In many ways, using Visual Studio to create custom user controls is similar to creating derived forms. Drag and drop the desired controls unto the user control, size them, and position with anchoring and docking as needed.

Activity - Creating a User Control Class

In order to access the contents of the TextBoxes on our composite control, one needs to write Property methods inside the NameUserControl class.

      public TextBox LastNameTextBox {
         get { return lastNameTextBox; }
         set { lastNameTextBox = value; }
      }

Likewise, events should be handled by methods inside the user control class

Custom Controls

Sometimes you might desire to build a brand-new custom control from scratch different from any of the built-in controls.

Custom controls derive from the base class Control. You will need to write the methods that paint the control on the screen.

How to: Develop a Simple Windows Forms Control

Activity - Creating a Custom Control Class

      [Category("Alignment"), Description("Specifies the alignment of text.")]
      private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
      public ContentAlignment Alignment
      {
         get{return alignmentValue;}
         set{
            alignmentValue = value;
            Invalidate();
         }
      }
      protected override void OnPaint(PaintEventArgs pe)
      {
         base.OnPaint(pe);

         StringFormat style = new StringFormat();
         style.Alignment = StringAlignment.Near;
         switch (alignmentValue)
         {
            case ContentAlignment.MiddleLeft:
               style.Alignment = StringAlignment.Near;
               break;
            case ContentAlignment.MiddleRight:
               style.Alignment = StringAlignment.Far;
               break;
            case ContentAlignment.MiddleCenter:
               style.Alignment = StringAlignment.Center;
               break;
         }

         pe.Graphics.DrawString(
             Text,
             Font,
             new SolidBrush(ForeColor),
             ClientRectangle, style);
      }

URL: http://www/cwu.edu /~gellenbe/446/labs/lab6.php
Author: Ed Gellenbeck, Department of Computer Science, Central Washington University, gellenbe@cwu.edu
Copyright 2006 Ed Gellenbeck, Central Washington University
Last modified: March 22, 2008