16.3 Handling Web Control Events

 <  Day Day Up  >  

You want to create an event handler to respond to an event fired from a Web Form control.


Technique

To create an event handler for a Web Form control, select the control within the designer and click the Events toolbar button located in the Property Browser. The Property Browser displays a list of valid events for a control. To create an event handler for a specific event, either double-click the event field to create a handler with a default name or enter a different name for the event handler. In Listing 16.1, you can see the code-behind file for a Web application created for this recipe called Web Shell. In the code listing, you can see how a delegate is created for an ImageButton control and associated with the Click event. The code for the event handler simply toggles the value of a Boolean variable and sets the visibility of TextBox control accordingly . A few things in this code are worth noting.

In the ImageButton.Click event handler, you can see a Boolean member variable being used. The member itself is declared static. If it weren't, then its value would not persist each time the page loads, which happens whenever a post back occurs. In other words, if the variable were not static, then even after it was changed within the event handler, it would be reset to its initialization value. Recipe 16.12, "Managing Application and Session State," demonstrates how to persist objects using the ViewState collection, and Recipe 16.13, "Creating Custom Web Controls," shows how to use session tracking.

Listing 16.1 Web Shell Code-Behind 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; using System.IO; namespace _3_EventHandling {     public class WebForm1 : System.Web.UI.Page     {         protected System.Web.UI.WebControls.TextBox ShellBox;         protected System.Web.UI.WebControls.Label Label1;         protected System.Web.UI.WebControls.ImageButton btnMinimize;         static private string curDir;         static protected bool bIsMinimized;         private void Page_Load(object sender, System.EventArgs e)         {             if( !Page.IsPostBack )             {                 curDir = Server.MapPath( "." );                 ShellBox.Text = "Welcome to WebShell\n";                 DisplayPrompt();             }             else             {                 // get command                 string cmd = ShellBox.Text.Substring(                     ShellBox.Text.LastIndexOf( '>' )+1);                 if( cmd != null && cmd != "" )                 {                     string ret = ProcessCommand( cmd );                     ShellBox.Text = ShellBox.Text + "\n" + ret + "\n";                     DisplayPrompt();                 }                 if( bIsMinimized == true )                     ShellBox.Visible = false;                 else                     ShellBox.Visible = true;             }         }         private string ProcessCommand( string cmd )         {             string ret = "";             switch( cmd )             {                 case( "ver" ):                 {                     ret =  "WebShell Version 1.0";                     break;                 }                 case ("cls"):                 {                     ShellBox.Text = "";                     ret = "";                     break;                 }                 case ( "dir" ):                 {                     DirectoryInfo di = new DirectoryInfo(curDir);                     FileInfo[] fi = di.GetFiles();                     foreach (FileInfo fiTemp in fi)                         ret = ret + fiTemp.Name + "\n";                     break;                 }                 default:                 {                     ret = cmd + "' is not recognized as an internal or " +                           "external command, operable program or batch file.";                     break;                 }             }             return ret;         }         private void DisplayPrompt()         {             ShellBox.Text = ShellBox.Text + curDir + ">";         }         #region Web Form Designer generated code         override protected void OnInit(EventArgs e)         {             InitializeComponent();             base.OnInit(e);         }         private void InitializeComponent()         {             this.btnMinimize.Click += new                 System.Web.UI.ImageClickEventHandler(this.btnMinimize_Click);             this.Load += new System.EventHandler(this.Page_Load);         }         #endregion         private void btnMinimize_Click(object sender,             System.Web.UI.ImageClickEventArgs e)         {             if( bIsMinimized == true )             {                 ShellBox.Visible = true;                 bIsMinimized = false;             }             else             {                 ShellBox.Visible = false;                 bIsMinimized = true;             }         }     } } 

When using event handlers, you must be cognizant of the order of method calls for each load of an ASP.NET page. Because each post back requires your class to be reconstructed using the information in the ViewState collection, the class initialization functions are called again. This process occurs before the actual event handler is called. In the Page_Load method in Listing 16.1, you can see how to check whether the page is being loaded in response to a post back by checking the IsPostBack property. If the page is a post back, you can also see that the TextBox.Visible property is changed. It might seem logical to simply change the controlling Boolean variable within the event handler, thinking that the Page_Load method controls the TextBox properly. However, the event handler for the ImageButton is called after the Page_Load method, which means the Boolean value is wrong at the time of Page_Load . You should ensure that control properties that rely on member variables which themselves might change within an event handler are set within the event handler as well as within the proper initialization methods .

Comments

The event-handler code is created within the code-behind file for the ASP.NET page. ASP.NET event handlers are created and associated with events in the same way as their Windows Forms counterparts and all other classes within the .NET Framework, by using delegates. Furthermore, each event-handler delegate remains consistent in its use of parameters. The first parameter to every delegate is always a System.Object representing the sender of the event. The second and last parameter is either an EventArgs object or a class derived from EventArgs to supply additional information. In other words, a large part of the discussion in Chapter 8, "Windows Forms Controls," regarding the creation of event handlers applies equally to Web Form controls as they do to Windows Forms controls.

The previous recipe noted that ASP.NET controls are translated into HTML for rendering in a user 's browser. This process means that you can also create client-side events in order to prevent making a trip back to the server to update the form accordingly. Listing 16.2 shows the .aspx file that accompanies the code-behind file in Listing 16.1. In this listing, you can see several JavaScript methods that are processed within the user's browser as they manipulate the controls. These methods are attached to various events of the HTML form object that is created when the project is initially created. Within the body of the ASP.NET page, you can see a few server-side controls. One of them is a label control named Titlebar . One of the attributes is named onclick and contains a call to the JavaScript alert method. Within the Integrated Development Environment (IDE), a small red wavy line appears underneath this attribute because onclick is not defined for a label control. Rather than disregard the attribute, however, ASP.NET simply passes the attribute to the HTML page, which in turn creates a JavaScript event handler. You can optionally add the onclick attribute to your code-behind file. Each control contains an Attributes collection, which translates into the attributes of the final HTML code.

Listing 16.2 Web Shell ASP.NET Page
 <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" graphics/ccc.gif Inherits="_3_EventHandling.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML>     <HEAD>         <title>WebShell 1.0</title>         <meta name="vs_snapToGrid" content="False">         <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">         <meta content="C#" name="CODE_LANGUAGE">         <meta content="JavaScript" name="vs_defaultClientScript">         <meta content="http://schemas.microsoft.com/intellisense/ie5"             name="vs_targetSchema">         <script language="javascript" id="clientEventHandlersJS"> <!-- function getkey(e) {     if (window.event)         return window.event.keyCode;     else if (e)         return e.which;     else         return null; } function Form1_onkeypress() {     if( getkey(event) == 13 )     {         Form1.submit();     }     else     {         window.status = "Key Pressed: " + getkey(event);         setShellBoxFocus();     } } function setShellBoxFocus() {     if( document.Form1.ShellBox != null )     {         document.Form1.ShellBox.focus();         var oRng = document.Form1.ShellBox.createTextRange();         oRng.collapse(false);         oRng.select();     } } function window_onload() {     setShellBoxFocus(); } function Form1_onmouseup() {     setShellBoxFocus(); } //-->     </script>     </HEAD>     <body language="javascript" onload="return window_onload()"         ms_positioning="GridLayout">         <form language="javascript" onkeypress="return Form1_onkeypress()"            id="Form1" method="post" runat="server"            onmouseup="return Form1_onmouseup()">             <P align="center">                 <asp:textbox id="ShellBox" runat="server" Width="759px"                     Height="488px" TextMode="MultiLine" BackColor="Black"                     ForeColor="White" AutoPostBack="True"                     style="Z-INDEX: 101; LEFT: 256px; POSITION:                     absolute; TOP: 56px"></asp:textbox>             </P>             <DIV style="Z-INDEX: 102; LEFT: 256px; WIDTH: 765px;                 POSITION: absolute; TOP: 24px; HEIGHT: 43px"                 ms_positioning="GridLayout">                 <asp:Label onclick="alert('Web Shell 1.0');" id="Titlebar"                     style="Z-INDEX: 101; LEFT: 0px; POSITION: absolute;                     TOP: 11px" runat="server" Width="760px" Height="24px"                     ForeColor="White" BackColor="Blue">Web Shell 1.0</asp:Label>                 <asp:ImageButton id="btnMinimize" style="Z-INDEX: 102;                     LEFT: 731px; POSITION: absolute; TOP: 12px"                     runat="server" ImageUrl="minimize.jpg"></asp:ImageButton>             </DIV>             <P align="center">&nbsp;</P>         </form>     </body> </HTML> 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net