asp.net.ph

Skip Navigation Links

Handling User Control Events

ASP.NET Web Forms   Web Forms Server Controls   Web Forms User Controls


There is little difference between writing event-handling methods for a user control and writing the same for a Web Forms page. Keep in mind, however, that user controls encapsulate their own events and send the event information through the containing page to be processed. Do not include user control event handlers in the containing page; write them in the code declaration block of the user control or in the code-behind file that generates the user control.

NOTE: For information on how to create event handlers for ASP.NET server controls, see Defining Web Forms Event-Handling Methods.

To encapsulate user control events in the control

  1. Include a code declaration block in the user control that contains event-handling code for your form.

NOTE: You must include all server controls involved in the user control’s events in the user control itself or use the FindControl method to locate and access a particular control’s functionality.

The following code, included in a file with the .ascx extension, will run when the Button Web server control is clicked.

<script language="C#" runat="server">
void SubmitBtn_Click ( object src, EventArgs e ) {
   myLabel.Text += "Your user id is " + User.Text + "<br>";
   myLabel.Text += "Your password is " + Pass.Text + "<br>";
}
</script>

<script language="C#" runat="server">
public String UserId {
   get {
      return User.Text;
   }
   set {
      User.Text = value;
   }
}

public String Password {
   get {
      return Pass.Text;
   }
   set {
      Pass.Text = value;
   }
} 
</script>

<table>
<tr>
   <td><b>Login: </b></td>
   <td><ASP:TextBox id="User" runat="server"/></td></tr>

<tr>
   <td><b>Password: </b></td>
   <td><ASP:TextBox id="Pass" TextMode="Password" runat="server"/></td></tr>

<tr>
   <td></td>
   <td><ASP:Button Text="Click Here" OnClick="SubmitBtn_Click" runat="server"/></td></tr>

<tr>
   <td ColSpan=2><ASP:Label id="myLabel" runat="server"/></td></tr>
</table>
  C# VB
  1. Declare the user control in the Web Forms pages where you want the user control to appear.

NOTE: The code in this procedure interacts with the code from Including a User Control in a Web Forms Page.

See Also

Creating a User Control   Including a User Control in Another Web Forms Page   Defining Web Forms Event-Handling Methods   Handling User Control Events



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note