FREE BOOK

Chapter 5: Event-Based Programming

Posted by Apress Free Book | ASP.NET January 02, 2009
In this chapter, we explore the intricacies of working with server control events.

Using the Textbox Control on a Web Form

The Textbox Web Form shown in the Design view in Figure 5-4 hosts the newly minted Textbox control with its TextChanged event capabilities.



Figure 5-4. Server-side control events in ASP.NET

The Web Form contains an instance of our Textbox control named NameTextbox, along with a Label control named ChangeLabel that is used to indicate the raising of TextChanged event. The label is programmatically set to a value of "No change!" along with the current time by default during the loading of the Web Form. Raising the TextChanged event causes the event-handling code to set the label's value to "Changed." along with the current time. This allows you to recycle the control several times to verify that the event is working properly.

The TextChanged event of the NameTextbox control is visible when you select the control in the Design view of Visual Studio .NET and look at it in the Properties window, as shown in Figure 5-5. Click the lightning bolt icon to categorize the properties by events and you will see TextChanged. We used an event handler called Name_TextChanged as a client subscriber to the TextChanged event. The full extent of our code work is shown in Listings 5-3 and 5-4.



Figure 5-5. The Server-side events tab of the Properties window

Listing 5-3. The Textbox Web Form .aspx Page File

<%@ Page language="c#" Codebehind="Textbox.aspx.cs" AutoEventWireup="false"
Inherits="ControlsBookWeb.Ch05.Textbox" %>
<%@ Register TagPrefix="apress" Namespace="ControlsBookLib.Ch05"
Assembly="ControlsBookLib" %>
<%@ Register TagPrefix="apressUC" TagName="ControlsBookHeader"
Src="..\ControlsBookHeader.ascx" %>
<%@ Register TagPrefix="apressUC" TagName="ControlsBookFooter"
Src="..\ControlsBookFooter.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<
HEAD>
<
title>Ch05 Textbox</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5"

</
HEAD>
<
body MS_POSITIONING="FlowLayout">
<form id="Textbox" method="post" runat="server">
<apressUC:ControlsBookHeader id="Header" runat="server"
ChapterNumber="5" ChapterTitle="Event-based Programming" />
<h3>Ch05 TextBox</h3>
Enter your name:<br>
<apress:textbox id="NameTextbox" runat="server"></apress:textbox><br>
<br>
<
asp:button id="SubmitPageButton" runat="server" Text=
"Submit Page"></asp:button><br>
<
br>
<
asp:label id="ChangeLabel" runat="server" Text=""></asp:label><br>\
<apressUC:ControlsBookFooter id="Footer" runat="server" />
</form>
</
body>
</
HTML>

Listing 5-4. The Textbox Web Form Code-Behind Class File

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 ControlsBookWeb.Ch05
{
    public class Textbox : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button SubmitPageButton;
        protected ControlsBookLib.Ch05.Textbox NameTextbox;
        protected System.Web.UI.WebControls.Label ChangeLabel;
        private void Page_Load(object sender, System.EventArgs e)
        {
            ChangeLabel.Text = DateTime.Now.ToLongTimeString() + ": No change.";
        }
        #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.NameTextbox.TextChanged += new
            System.EventHandler(this.Name_TextChanged);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
        private void Name_TextChanged(object sender, System.EventArgs e)
        {
            ChangeLabel.Text = DateTime.Now.ToLongTimeString() + ": Changed!";
        }
    }
}


The event wiring is conducted inside the InitializeComponent routine:

    private void InitializeComponent()
    {
        this.NameTextbox.TextChanged += new System.EventHandler(this.Name_TextChanged);
        this.Load += new System.EventHandler(this.Page_Load);
    }

The Name_TextChanged method is wrapped by a System.EventHandler delegate and then passed to the TextChanged event of our custom Textbox control to add it to its delegate invocation list. Notice also the wiring up of the Page_Load method to the Load event that the Page class will raise during request processing.

The execution of the Web Form during the initial page request results in the UI output of Figure 5-6. The ViewState rendered by the control into this Web Form shows the Text property as a blank value. We entered a name into the Textbox as well, but we haven't clicked the button to submit the Web Form via postback.



Figure 5-6. Initial rendering of the Textbox control

Upon clicking the button to execute a postback to the web server, the Textbox control will read the blank value from ViewState and find the name value "Dale Michalk" when the ASP.NET invokes LoadPostData. Because the posted data is different from the current ViewState value, it calls its internal OnTextChanged method to raise events to all registered delegate subscribers. This results in the Name_TextChanged event handler method firing, and the code that changes the label to reflect the new value executes:

    private void Name_TextChanged(object sender, System.EventArgs e)
    {
        ChangeLabel.Text = DateTime.Now.ToLongTimeString() + ": Changed!";
    }


The result is that ChangeLabel displays the text containing the current time and the word "Changed!" as shown in Figure 5-7.



Figure 5-7. The firing of the TextChanged event by the Textbox control

The next step in this demonstration is to recycle the page without changing the value in the Textbox control by simply clicking the Submit Page button. Because the ViewState and the control's text post data contain the same value of "Dale Michalk," no event is raised. The increment of the timestamp in the label in Figure 5-8 confirms that the page was processed successfully. Our control is able to react appropriately to changes of its Text property.



Figure 5-8. The firing of the TextChanged event by the Textbox control

Total Pages : 12 34567
Image Loading...