ASP.NET 4 Unleashed
Exposing Events in User Controls
A user control can contain the same event-handling subroutines as a normal ASP.NET page. For example, you can add a Page_Load subroutine to a user control that executes before any content in the body of the control is rendered. The Page_Load subroutine contained in the user control is completely distinct from the Page_Load subroutine in the parent page. The user control in Listing 5.16 randomly displays one of three quotes every time it is displayed. Listing 5.16 UserControlEvents.ascx
<Script Runat="Server"> Sub Page_Load Dim RanNum As New Random Select Case RanNum.Next( 3 ) Case 0 lblQuote.Text = "A penny saved is a penny earned" Case 1 lblQuote.Text = "Look before you leap" Case 2 lblQuote.Text = "He who hesitates is lost" End Select End Sub </Script> <asp:Label id="lblQuote" Runat="Server" /> The C# version of this code can be found on the CD-ROM. The page in Listing 5.17 uses this user control to randomly display a quotation. Listing 5.17 DisplayControlEvents.aspx
<%@ Register TagPrefix="SuperCompany" TagName="Quote" Src="ControlEvents.ascx" %> <SuperCompany:Quote Runat="Server" /> The C# version of this code can be found on the CD-ROM. |