A�adiendo eventos a los controles
Ahora vamos a a�adir un evento a un control de servidor, dicho evento ejecutar� c�digo C# para realizar una acci�n en concreto.
Primero vamos a la vista de dise�o, en la que podremos ver la caja de texto, la etiqueta y el bot�n. Seguidamente a�adiremos un evento al bot�n para que cuando sea pulsado se ejecute una acci�n en el servidor. Para a�adir el evento de clic al bot�n pulsaremos doble clic sobre el bot�n en la ventana de dise�o del formulario.
Esto nos llevar� a la ventana de edici�n de c�digo C#, en la que se nos habr� creado un m�todo btnEnviar_Click() que se habr� asociado con el evento clic del bot�n.
En este m�todo escribiremos el c�digo que queremos que se ejecute cuando se pulsa clic sobre el bot�n "Enviar". Sencillamente vamos a agregar a la etiqueta el valor de la caja de texto.
private void btnEnviar_Click(object sender, System.EventArgs e)
{
lblNombre.Text+= txtNombre.Text;
}
Con lo que tendremos el siguiente c�digo:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebEstiloEjemplos.ejem01
{
/// <summary>
/// Summary description for Ejemplo01.
/// </summary>
public class Ejemplo01 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtNombre;
protected System.Web.UI.WebControls.Label lblNombre;
protected System.Web.UI.WebControls.Button btnEnviar;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnEnviar.Click += new System.EventHandler(this.btnEnviar_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnEnviar_Click(object sender, System.EventArgs e)
{
lblNombre.Text+= txtNombre.Text;
}
}
}