Export (0) Print
Expand All

UserControl Class

Provides an empty control that can be used to create other controls.

For a list of all members of this type, see UserControl Members.

System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         System.Windows.Forms.Control
            System.Windows.Forms.ScrollableControl
               System.Windows.Forms.ContainerControl
                  System.Windows.Forms.UserControl

[Visual Basic]
Public Class UserControl
   Inherits ContainerControl
[C#]
public class UserControl : ContainerControl
[C++]
public __gc class UserControl : public ContainerControl
[JScript]
public class UserControl extends ContainerControl

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

By extending ContainerControl, UserControl inherits all the standard positioning and mnemonic-handling code that is necessary in a user control.

The UserControl gives you the ability to create controls that can be used in multiple places within an application or organization. You can include all the code needed for validation of common data you ask the user to input; some examples of this are e-mail addresses (see Example section), telephone numbers, and postal codes. Another efficient use of the user control is to simply preload a ComboBox or ListBox with static items you commonly use in almost every application; some examples of this are countries/regions, cities, states, and office locations.

Note   You might consider creating a namespace that contains several classes of user controls and compiling it into one DLL. This DLL can be referenced and distributed with the application or all applications within an organization. This gives you the ability to reference the user control in many applications and save time laying out and coding the contained elements of the user control. A user control also gives you consistency within or across applications; for example, all address information input blocks will all have the same appearance and behavior. Consistency gives your application a more polished and professional appearance.

Example

[Visual Basic, C#, C++] The following example creates a UserControl that can be reused in multiple applications to get user information. This example adds several Label controls, TextBox controls and an ErrorProvider object to the UserControl to gather the user's information. Additionally, the user's e-mail address is validated in the Validating event of the TextBox and the ErrorProvider object is used to give the user feedback if the data fails validation. The code is intended to be compiled into a DLL for reference in other applications.

[Visual Basic] 
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Namespace UserControls

   Public Class MyCustomerInfoUserControl
      Inherits System.Windows.Forms.UserControl

      ' Create the controls.
      Private errorProvider1 As System.Windows.Forms.ErrorProvider
      Private textName As System.Windows.Forms.TextBox
      Private textAddress As System.Windows.Forms.TextBox
      Private textCity As System.Windows.Forms.TextBox
      Private textStateProvince As System.Windows.Forms.TextBox
      Private textPostal As System.Windows.Forms.TextBox
      Private textCountryRegion As System.Windows.Forms.TextBox
      Private WithEvents textEmail As System.Windows.Forms.TextBox
      Private labelName As System.Windows.Forms.Label
      Private labelAddress As System.Windows.Forms.Label
      Private labelCityStateProvincePostal As System.Windows.Forms.Label
      Private labelCountryRegion As System.Windows.Forms.Label
      Private labelEmail As System.Windows.Forms.Label
      Private components As System.ComponentModel.IContainer        
        
      ' Define the constructor.
      Public Sub New()
         InitializeComponent()
      End Sub        
        
      ' Initialize the control elements.
      Public Sub InitializeComponent()
         ' Initialize the controls.
         components = New System.ComponentModel.Container()
         errorProvider1 = New System.Windows.Forms.ErrorProvider()
         textName = New System.Windows.Forms.TextBox()
         textAddress = New System.Windows.Forms.TextBox()
         textCity = New System.Windows.Forms.TextBox()
         textStateProvince = New System.Windows.Forms.TextBox()
         textPostal = New System.Windows.Forms.TextBox()
         textCountryRegion = New System.Windows.Forms.TextBox()
         textEmail = New System.Windows.Forms.TextBox()
         labelName = New System.Windows.Forms.Label()
         labelAddress = New System.Windows.Forms.Label()
         labelCityStateProvincePostal = New System.Windows.Forms.Label()
         labelCountryRegion = New System.Windows.Forms.Label()
         labelEmail = New System.Windows.Forms.Label()
           
         ' Set the tab order, text alignment, size, and location of the controls.
         textName.Location = New System.Drawing.Point(120, 8)
         textName.Size = New System.Drawing.Size(232, 20)
         textName.TabIndex = 0

         textAddress.Location = New System.Drawing.Point(120, 32)
         textAddress.Size = New System.Drawing.Size(232, 20)
         textAddress.TabIndex = 1

         textCity.Location = New System.Drawing.Point(120, 56)
         textCity.Size = New System.Drawing.Size(96, 20)
         textCity.TabIndex = 2

         textStateProvince.Location = New System.Drawing.Point(216, 56)
         textStateProvince.Size = New System.Drawing.Size(56, 20)
         textStateProvince.TabIndex = 3

         textPostal.Location = New System.Drawing.Point(272, 56)
         textPostal.Size = New System.Drawing.Size(80, 20)
         textPostal.TabIndex = 4

         textCountryRegion.Location = New System.Drawing.Point(120, 80)
         textCountryRegion.Size = New System.Drawing.Size(232, 20)
         textCountryRegion.TabIndex = 5

         textEmail.Location = New System.Drawing.Point(120, 104)
         textEmail.Size = New System.Drawing.Size(232, 20)
         textEmail.TabIndex = 6

         labelName.Location = New System.Drawing.Point(8, 8)
         labelName.Size = New System.Drawing.Size(112, 23)
         labelName.Text = "Name:"
         labelName.TextAlign = System.Drawing.ContentAlignment.MiddleRight

         labelAddress.Location = New System.Drawing.Point(8, 32)
         labelAddress.Size = New System.Drawing.Size(112, 23)
         labelAddress.Text = "Address:"
         labelAddress.TextAlign = System.Drawing.ContentAlignment.MiddleRight

         labelCityStateProvincePostal.Location = New System.Drawing.Point(8, 56)
         labelCityStateProvincePostal.Size = New System.Drawing.Size(112, 23)
         labelCityStateProvincePostal.Text = "City, St/Prov. Postal:"
         labelCityStateProvincePostal.TextAlign = System.Drawing.ContentAlignment.MiddleRight

         labelCountryRegion.Location = New System.Drawing.Point(8, 80)
         labelCountryRegion.Size = New System.Drawing.Size(112, 23)
         labelCountryRegion.Text = "Country/Region:"
         labelCountryRegion.TextAlign = System.Drawing.ContentAlignment.MiddleRight

         labelEmail.Location = New System.Drawing.Point(8, 104)
         labelEmail.Size = New System.Drawing.Size(112, 23)
         labelEmail.Text = "email:"
         labelEmail.TextAlign = System.Drawing.ContentAlignment.MiddleRight
          
         ' Add the controls to the user control.
         Controls.AddRange(New System.Windows.Forms.Control() {labelName, _
           labelAddress, labelCityStateProvincePostal, labelCountryRegion, _
           labelEmail, textName, textAddress, textCity, textStateProvince, _
           textPostal, textCountryRegion, textEmail})
            
         ' Size the user control.
         Size = New System.Drawing.Size(375, 150)
      End Sub        

      Private Sub MyValidatingCode()
         ' Confirm there is text in the control.
         If textEmail.Text.Length = 0 Then
            Throw New Exception("Email address is a required field")
         Else
            ' Confirm that there is a "." and an "@" in the e-mail address.
            If textEmail.Text.IndexOf(".") = - 1 Or textEmail.Text.IndexOf("@") = - 1 Then
               Throw New Exception("Email address must be valid e-mail address format." + _
                 Microsoft.VisualBasic.ControlChars.Cr + "For example 'someone@example.com'")
            End If
         End If
      End Sub 

      ' Validate the data input by the user into textEmail.
      Private Sub textEmail_Validating(sender As Object, _
                                       e As System.ComponentModel.CancelEventArgs) Handles textEmail.Validating
         Try
            MyValidatingCode()
   
         Catch ex As Exception
            ' Cancel the event and select the text to be corrected by the user.
            e.Cancel = True
            textEmail.Select(0, textEmail.Text.Length)
      
            ' Set the ErrorProvider error with the text to display. 
            Me.errorProvider1.SetError(textEmail, ex.Message)
         End Try
      End Sub 


      Private Sub textEmail_Validated(sender As Object, _
                                      e As System.EventArgs) Handles textEmail.Validated
         ' If all conditions have been met, clear the error provider of errors.
         errorProvider1.SetError(textEmail, "")
      End Sub        

   End Class
End Namespace

[C#] 
using System;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace UserControls 
{
   public class MyCustomerInfoUserControl : System.Windows.Forms.UserControl 
   {
      // Create the controls.
      private System.Windows.Forms.ErrorProvider errorProvider1;
      private System.Windows.Forms.TextBox textName;
      private System.Windows.Forms.TextBox textAddress;
      private System.Windows.Forms.TextBox textCity;
      private System.Windows.Forms.TextBox textStateProvince;
      private System.Windows.Forms.TextBox textPostal;
      private System.Windows.Forms.TextBox textCountryRegion;
      private System.Windows.Forms.TextBox textEmail;
      private System.Windows.Forms.Label labelName;
      private System.Windows.Forms.Label labelAddress;
      private System.Windows.Forms.Label labelCityStateProvincePostal;
      private System.Windows.Forms.Label labelCountryRegion;
      private System.Windows.Forms.Label labelEmail;
      private System.ComponentModel.IContainer components;

      // Define the constructor.
      public MyCustomerInfoUserControl() 
      {
         InitializeComponent();
      }
 
      // Initialize the control elements.
      public void InitializeComponent() 
      {
         // Initialize the controls.
         components = new System.ComponentModel.Container();
         errorProvider1 = new System.Windows.Forms.ErrorProvider();
         textName = new System.Windows.Forms.TextBox();
         textAddress = new System.Windows.Forms.TextBox();
         textCity = new System.Windows.Forms.TextBox();
         textStateProvince = new System.Windows.Forms.TextBox();
         textPostal = new System.Windows.Forms.TextBox();
         textCountryRegion = new System.Windows.Forms.TextBox();
         textEmail = new System.Windows.Forms.TextBox();
         labelName = new System.Windows.Forms.Label();
         labelAddress = new System.Windows.Forms.Label();
         labelCityStateProvincePostal = new System.Windows.Forms.Label();
         labelCountryRegion = new System.Windows.Forms.Label();
         labelEmail = new System.Windows.Forms.Label();

         // Set the tab order, text alignment, size, and location of the controls.
         textName.Location = new System.Drawing.Point(120, 8);
         textName.Size = new System.Drawing.Size(232, 20);
         textName.TabIndex = 0;

         textAddress.Location = new System.Drawing.Point(120, 32);
         textAddress.Size = new System.Drawing.Size(232, 20);
         textAddress.TabIndex = 1;

         textCity.Location = new System.Drawing.Point(120, 56);
         textCity.Size = new System.Drawing.Size(96, 20);
         textCity.TabIndex = 2;

         textStateProvince.Location = new System.Drawing.Point(216, 56);
         textStateProvince.Size = new System.Drawing.Size(56, 20);
         textStateProvince.TabIndex = 3;

         textPostal.Location = new System.Drawing.Point(272, 56);
         textPostal.Size = new System.Drawing.Size(80, 20);
         textPostal.TabIndex = 4;

         textCountryRegion.Location = new System.Drawing.Point(120, 80);
         textCountryRegion.Size = new System.Drawing.Size(232, 20);
         textCountryRegion.TabIndex = 5;

         textEmail.Location = new System.Drawing.Point(120, 104);
         textEmail.Size = new System.Drawing.Size(232, 20);
         textEmail.TabIndex = 6;

         labelName.Location = new System.Drawing.Point(8, 8);
         labelName.Size = new System.Drawing.Size(112, 23);
         labelName.Text = "Name:";
         labelName.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

         labelAddress.Location = new System.Drawing.Point(8, 32);
         labelAddress.Size = new System.Drawing.Size(112, 23);
         labelAddress.Text = "Address:";
         labelAddress.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

         labelCityStateProvincePostal.Location = new System.Drawing.Point(8, 56);
         labelCityStateProvincePostal.Size = new System.Drawing.Size(112, 23);
         labelCityStateProvincePostal.Text = "City, St/Prov. Postal:";
         labelCityStateProvincePostal.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

         labelCountryRegion.Location = new System.Drawing.Point(8, 80);
         labelCountryRegion.Size = new System.Drawing.Size(112, 23);
         labelCountryRegion.Text = "Country/Region:";
         labelCountryRegion.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

         labelEmail.Location = new System.Drawing.Point(8, 104);
         labelEmail.Size = new System.Drawing.Size(112, 23);
         labelEmail.Text = "email:";
         labelEmail.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

         // Add the Validating and Validated handlers for textEmail.
         textEmail.Validating += new System.ComponentModel.CancelEventHandler(textEmail_Validating);
         textEmail.Validated += new System.EventHandler(textEmail_Validated);

         // Add the controls to the user control.
         Controls.AddRange(new System.Windows.Forms.Control[] 
         {
            labelName,
            labelAddress,
            labelCityStateProvincePostal,
            labelCountryRegion,
            labelEmail,
            textName,
            textAddress,
            textCity,
            textStateProvince,
            textPostal,
            textCountryRegion,
            textEmail
         });  

         // Size the user control.
         Size = new System.Drawing.Size(375, 150);
      }   


      private void MyValidatingCode()
      {
         // Confirm there is text in the control.
         if (textEmail.Text.Length == 0)
         {
            throw new Exception("Email address is a required field.");
         }
         // Confirm that there is a "." and an "@" in the e-mail address.
         else if(textEmail.Text.IndexOf(".") == -1 || textEmail.Text.IndexOf("@") == -1)
         {
            throw new Exception("Email address must be valid e-mail address format." +
             "\nFor example: 'someone@example.com'");
         }
      }


      // Validate the data input by the user into textEmail.
      private void textEmail_Validating(object sender, System.ComponentModel.CancelEventArgs e)
      { 
         try
         {
            MyValidatingCode();
         }

         catch(Exception ex)
         {
            // Cancel the event and select the text to be corrected by the user.
            e.Cancel = true;
            textEmail.Select(0, textEmail.Text.Length);

            // Set the ErrorProvider error with the text to display. 
            this.errorProvider1.SetError(textEmail,ex.Message);
          }
      }   


      private void textEmail_Validated(Object sender, System.EventArgs e)
      {
         //If all conditions have been met, clear the error provider of errors.
         errorProvider1.SetError(textEmail, "");
      }

   } // End Class   
} // End Namespace


[C++] 
#using <mscorlib.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;
using namespace System::ComponentModel;

namespace UserControls 
{
   public __gc class MyCustomerInfoUserControl : public System::Windows::Forms::UserControl 
   {
      // Create the controls.
private:
      System::Windows::Forms::ErrorProvider* errorProvider1;
      System::Windows::Forms::TextBox* textName;
      System::Windows::Forms::TextBox* textAddress;
      System::Windows::Forms::TextBox* textCity;
      System::Windows::Forms::TextBox* textStateProvince;
      System::Windows::Forms::TextBox* textPostal;
      System::Windows::Forms::TextBox* textCountryRegion;
      System::Windows::Forms::TextBox* textEmail;
      System::Windows::Forms::Label* labelName;
      System::Windows::Forms::Label* labelAddress;
      System::Windows::Forms::Label* labelCityStateProvincePostal;
      System::Windows::Forms::Label* labelCountryRegion;
      System::Windows::Forms::Label* labelEmail;
      System::ComponentModel::IContainer* components;

public:
      // Define the constructor.
      MyCustomerInfoUserControl() 
      {
         InitializeComponent();
      }
 
      // Initialize the control elements.
      void InitializeComponent() 
      {
         // Initialize the controls.
         components = new System::ComponentModel::Container();
         errorProvider1 = new System::Windows::Forms::ErrorProvider();
         textName = new System::Windows::Forms::TextBox();
         textAddress = new System::Windows::Forms::TextBox();
         textCity = new System::Windows::Forms::TextBox();
         textStateProvince = new System::Windows::Forms::TextBox();
         textPostal = new System::Windows::Forms::TextBox();
         textCountryRegion = new System::Windows::Forms::TextBox();
         textEmail = new System::Windows::Forms::TextBox();
         labelName = new System::Windows::Forms::Label();
         labelAddress = new System::Windows::Forms::Label();
         labelCityStateProvincePostal = new System::Windows::Forms::Label();
         labelCountryRegion = new System::Windows::Forms::Label();
         labelEmail = new System::Windows::Forms::Label();

         // Set the tab order, text alignment, size, and location of the controls.
         textName->Location = System::Drawing::Point(120, 8);
         textName->Size = System::Drawing::Size(232, 20);
         textName->TabIndex = 0;

         textAddress->Location = System::Drawing::Point(120, 32);
         textAddress->Size = System::Drawing::Size(232, 20);
         textAddress->TabIndex = 1;

         textCity->Location = System::Drawing::Point(120, 56);
         textCity->Size = System::Drawing::Size(96, 20);
         textCity->TabIndex = 2;

         textStateProvince->Location = System::Drawing::Point(216, 56);
         textStateProvince->Size = System::Drawing::Size(56, 20);
         textStateProvince->TabIndex = 3;

         textPostal->Location = System::Drawing::Point(272, 56);
         textPostal->Size = System::Drawing::Size(80, 20);
         textPostal->TabIndex = 4;

         textCountryRegion->Location = System::Drawing::Point(120, 80);
         textCountryRegion->Size = System::Drawing::Size(232, 20);
         textCountryRegion->TabIndex = 5;

         textEmail->Location = System::Drawing::Point(120, 104);
         textEmail->Size = System::Drawing::Size(232, 20);
         textEmail->TabIndex = 6;

         labelName->Location = System::Drawing::Point(8, 8);
         labelName->Size = System::Drawing::Size(112, 23);
         labelName->Text = S"Name:";
         labelName->TextAlign = System::Drawing::ContentAlignment::MiddleRight;

         labelAddress->Location = System::Drawing::Point(8, 32);
         labelAddress->Size = System::Drawing::Size(112, 23);
         labelAddress->Text = S"Address:";
         labelAddress->TextAlign = System::Drawing::ContentAlignment::MiddleRight;

         labelCityStateProvincePostal->Location = System::Drawing::Point(8, 56);
         labelCityStateProvincePostal->Size = System::Drawing::Size(112, 23);
         labelCityStateProvincePostal->Text = S"City, St/Prov. Postal:";
         labelCityStateProvincePostal->TextAlign = System::Drawing::ContentAlignment::MiddleRight;

         labelCountryRegion->Location = System::Drawing::Point(8, 80);
         labelCountryRegion->Size = System::Drawing::Size(112, 23);
         labelCountryRegion->Text = S"Country/Region:";
         labelCountryRegion->TextAlign = System::Drawing::ContentAlignment::MiddleRight;

         labelEmail->Location = System::Drawing::Point(8, 104);
         labelEmail->Size = System::Drawing::Size(112, 23);
         labelEmail->Text = S"email:";
         labelEmail->TextAlign = System::Drawing::ContentAlignment::MiddleRight;

         // Add the Validating and Validated handlers for textEmail.
         textEmail->Validating += new System::ComponentModel::CancelEventHandler(this, &MyCustomerInfoUserControl::textEmail_Validating);
         textEmail->Validated += new System::EventHandler(this, &MyCustomerInfoUserControl::textEmail_Validated);

         // Add the controls to the user control.

         System::Windows::Forms::Control* temp0 [] = {
            labelName,
            labelAddress,
            labelCityStateProvincePostal,
            labelCountryRegion,
            labelEmail,
            textName,
            textAddress,
            textCity,
            textStateProvince,
            textPostal,
            textCountryRegion,
            textEmail};

         Controls->AddRange(temp0);  

         // Size the user control.
         Size = System::Drawing::Size(375, 150);
      }   

private:
      void MyValidatingCode()
      {
         // Confirm there is text in the control.
         if (textEmail->Text->Length == 0)
         {
            throw new Exception(S"Email address is a required field.");
         }
         // Confirm that there is a "." and an "@" in the e-mail address.
         else if(textEmail->Text->IndexOf(S".") == -1 || textEmail->Text->IndexOf(S"@") == -1)
         {
            throw new Exception(S"Email address must be valid e-mail address format.\nFor example: 'someone@example.com'");
         }
      }


      // Validate the data input by the user into textEmail.
      void textEmail_Validating(Object* /*sender*/, System::ComponentModel::CancelEventArgs* e)
      { 
         try
         {
            MyValidatingCode();
         }

         catch(Exception* ex)
         {
            // Cancel the event and select the text to be corrected by the user.
            e->Cancel = true;
            textEmail->Select(0, textEmail->Text->Length);

            // Set the ErrorProvider error with the text to display. 
            this->errorProvider1->SetError(textEmail,ex->Message);
          }
      }   

      void textEmail_Validated(Object* /*sender*/, System::EventArgs* /*e*/)
      {
         //If all conditions have been met, clear the error provider of errors.
         errorProvider1->SetError(textEmail, S"");
      }

   }; // End Class   
} // End Namespace

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Windows.Forms

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

See Also

UserControl Members | System.Windows.Forms Namespace | ContainerControl | Form

Show:
© 2014 Microsoft