Esta documentación está archivada y no tiene mantenimiento.

UserControl (Clase)

Proporciona un control vacío que se puede usar para crear otros controles.

Espacio de nombres: System.Windows.Forms
Ensamblado: System.Windows.Forms (en system.windows.forms.dll)

[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
public class UserControl : ContainerControl
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
public class UserControl extends ContainerControl
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
public class UserControl extends ContainerControl
No aplicable.

Extendiendo ContainerControl, UserControl hereda todo el código de control de teclas de acceso y de posición estándar necesario en un control de usuario.

UserControl proporciona la capacidad de crear controles que se pueden usar en varios lugares de una aplicación o de una organización. Puede incluir todo el código necesario para la validación de datos frecuentes que se solicitan al usuario; como ejemplos se pueden citar las direcciones de correo electrónico (vea la sección Ejemplo), los números de teléfono y los códigos postales. Otro uso conveniente del control de usuario es el de cargar previamente un ComboBox o un ListBox con elementos estáticos que se usan normalmente en casi todas las aplicaciones, como, por ejemplo, países, regiones, ciudades, provincias y ubicaciones de oficinas. Para obtener más información sobre cómo crear controles personalizados, vea Desarrollar controles personalizados de formularios Windows Forms con .NET Framework.

NotaNota:

Puede ser conveniente crear un espacio de nombres que contenga varias clases de controles de usuario y compilarlo en un archivo DLL. Este archivo DLL se puede usar como referencia y distribuir con una o todas las aplicaciones de una organización. De este modo, se tendrá la capacidad de hacer referencia al control de usuario en muchas aplicaciones y ahorrar tiempo a la hora de diseñar y codificar los elementos que contiene el control de usuario. Un control de usuario proporciona también coherencia dentro de una aplicación o entre aplicaciones. Por ejemplo, todos los bloques de entrada de información de direcciones tendrán los mismos comportamiento y aspecto. La coherencia hará que la aplicación tenga un aspecto más profesional y de mayor perfección.

Puede alojar clases derivadas de UserControl de formularios Windows Forms dentro de un formulario, en otro UserControl, dentro de Internet Explorer en una página Web o dentro de un control WebBrowser alojado en un formulario.

NotaNota:

Al alojar UserControl dentro del control WebBrowser, no se pueden desactivar los estilos visuales utilizando el valor de etiqueta METAMSThemeCompatible. Para obtener más información sobre los estilos visuales, vea Representar controles con estilos visuales

Tenga en cuenta que para las aplicaciones de Smartphone este control requiere la versión 5.0 de Windows Mobile para dispositivos Smartphone.

En el siguiente ejemplo de código se crea un UserControl que se puede volver a usar en muchas aplicaciones para obtener información del usuario. En este ejemplo se agregan varios controles Label, controles TextBox y un objeto ErrorProvider al UserControl para obtener información del usuario. Además, la dirección de correo electrónico del usuario se valida en el evento Validating del TextBox y el objeto ErrorProvider se utiliza para proporcionar información al usuario en caso de que la validación de datos no sea correcta. Se supone que el código se va a compilar en un archivo DLL que se podrá utilizar en otras aplicaciones.

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


package UserControls; 

import System.*;
import System.Windows.Forms.*;
import System.Drawing.*;
import System.ComponentModel.*;

public class MyCustomerInfoUserControl extends 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();
    } //MyCustomerInfoUserControl

    // 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.set_Location(new System.Drawing.Point(120, 8));
        textName.set_Size(new System.Drawing.Size(232, 20));
        textName.set_TabIndex(0);

        textAddress.set_Location(new System.Drawing.Point(120, 32));
        textAddress.set_Size(new System.Drawing.Size(232, 20));
        textAddress.set_TabIndex(1);

        textCity.set_Location(new System.Drawing.Point(120, 56));
        textCity.set_Size(new System.Drawing.Size(96, 20));
        textCity.set_TabIndex(2);

        textStateProvince.set_Location(new System.Drawing.Point(216, 56));
        textStateProvince.set_Size(new System.Drawing.Size(56, 20));
        textStateProvince.set_TabIndex(3);

        textPostal.set_Location(new System.Drawing.Point(272, 56));
        textPostal.set_Size(new System.Drawing.Size(80, 20));
        textPostal.set_TabIndex(4);

        textCountryRegion.set_Location(new System.Drawing.Point(120, 80));
        textCountryRegion.set_Size(new System.Drawing.Size(232, 20));
        textCountryRegion.set_TabIndex(5);

        textEmail.set_Location(new System.Drawing.Point(120, 104));
        textEmail.set_Size(new System.Drawing.Size(232, 20));
        textEmail.set_TabIndex(6);

        labelName.set_Location(new System.Drawing.Point(8, 8));
        labelName.set_Size(new System.Drawing.Size(112, 23));
        labelName.set_Text("Name:");
        labelName.set_TextAlign(System.Drawing.ContentAlignment.MiddleRight);

		labelAddress.set_Location(new System.Drawing.Point(8, 32));
        labelAddress.set_Size(new System.Drawing.Size(112, 23));
        labelAddress.set_Text("Address:");
        labelAddress.set_TextAlign(System.Drawing.ContentAlignment.MiddleRight);

        labelCityStateProvincePostal.set_Location(
            new System.Drawing.Point(8, 56));
        labelCityStateProvincePostal.set_Size(new System.Drawing.Size(112, 23));
        labelCityStateProvincePostal.set_Text("City, St/Prov. Postal:");
        labelCityStateProvincePostal.set_TextAlign(
            System.Drawing.ContentAlignment.MiddleRight);

        labelCountryRegion.set_Location(new System.Drawing.Point(8, 80));
        labelCountryRegion.set_Size(new System.Drawing.Size(112, 23));
        labelCountryRegion.set_Text("Country/Region:");
        labelCountryRegion.set_TextAlign(
            System.Drawing.ContentAlignment.MiddleRight);

        labelEmail.set_Location(new System.Drawing.Point(8, 104));
        labelEmail.set_Size(new System.Drawing.Size(112, 23));
        labelEmail.set_Text("email:");
        labelEmail.set_TextAlign(System.Drawing.ContentAlignment.MiddleRight);

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

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

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

    private void MyValidatingCode() throws Exception
    {
        // Confirm there is text in the control.
        if (textEmail.get_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.get_Text().IndexOf(".") == -1 ||
                    textEmail.get_Text().IndexOf("@") == -1) {
                throw new Exception("Email address must be valid e-mail"
                + "address format." + "\nFor example: 'someone@example.com'");
            }
        }
    } //MyValidatingCode

    // 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.set_Cancel(true);
            textEmail.Select(0, textEmail.get_Text().length());

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

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

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0
Mostrar: