Recipe 5.3 Creating a Custom Control with State

     

5.3.1 Problem

You want to create a custom control that remembers its state between postbacks of a form, like the server controls provided with ASP.NET.

5.3.2 Solution

Create a custom control like the one described in Recipe 5.2, implement the IPostBackDataHandler interface to add the functionality to retrieve the values posted to the server, and then update the values in the custom control from the postback data.

Use the .NET language of your choice to:

  1. Create a class that inherits from the Control class in the System.Web.UI namespace.

  2. Implement support for HTML-style attributes by adding properties to the class.

  3. Implement an IPostBackDataHandler as necessary to update the state of the control with the posted data.

  4. Override the Render method to have it render the HTML output of the control using the values of the properties.

To use the custom control in an ASP.NET page:

  1. Register the assembly containing the control.

  2. Insert the tag for the custom control anywhere in the page and set the attributes appropriately.

Example 5-7 and Example 5-8 show the VB and C# class files for a custom control that maintains state. Example 5-9 shows how we use the custom control in an ASP.NET page.

A version of the custom control that maintains state and provides the added ability to raise an event when the control data has changed is shown in Example 5-10 (VB) and Example 5-11 (C#). Example 5-12 through Example 5-14 show the .aspx and code-behind files of an application that uses the custom control with state and provides an event handler for the data-changed event.

5.3.3 Discussion

When implementing a custom control, you will want to make sure that it maintains its state between postback s to the server. Otherwise, it will lose its values and the user will have to reset them each time. To see what we mean by this, consider the custom controls discussed in Recipe 5.1 and Recipe 5.2; if you implement either of these controls, you will notice that anytime you click the Submit button, the value entered into the text box is lost when the page is redisplayed. This is caused by the control's not processing the form data posted back to the server.

To maintain the values in a custom control, it must, like all the controls provided with ASP.NET, implement the IPostBackDataHandler interface. The IPostBackDataHandler interface requires the implementation of two methods : LoadPostData and RaisePostDataChangedEvent . The LoadPostData method supplies the data posted to the server, which provides the ability to update the state of the control with the posted data. The RaisePostDataChangedEvent method provides the ability to raise events if data for the control changes; this method is used to good effect in the second of the two approaches we advocate for this recipe and is discussed at the end of this section. The LoadPostData and RaisePostDataChangedEvent methods are automatically called by ASP.NET when the form is posted back to the server.

The LoadPostData method has the following syntax:

 
figs/vbicon.gif
 LoadPostData(postDataKey As String, postCollection As NameValueCollection) 
figs/csharpicon.gif
 bool LoadPostData(string postDataKey, NameValueCollection postCollection); 

The postCollection argument contains the collection of name /value pairs posted to the server. The postDataKey parameter provides the "name" of the key value for this control that is used to access the control's postback value.

The postDataKey parameter will be set to the unique ID value for the custom control. If the custom control contains only one control that posts a value back to the server and its ID was used as the value of the "name" attribute when the control was rendered, the value of the postDataKey parameter can be used to obtain the posted value. If the custom control is instead a composite control that contains more than one control with postback data or if the custom control's ID was not used for the control within the custom control, you, as the programmer, will need to provide a unique ID value for each control in the custom control, extract the values individually within the LoadPostData method, and then set the appropriate property.

The return value for the LoadPostData method should always be set to False if the data has not changed or no check is performed to see if the data changed. Setting the return to False prevents the RaisePostDataChangedEvent method from being called. See the discussion at the end of this section regarding raising events on data changes.


To give you a better feel for how to implement this solution, we now turn to a variation of the custom control we've been working with throughout the chapter, which contains a label and text box. In our first example, the control needs to simply remember the state of the text in the text box of the input HTML control, and so we have added a text property to provide the ability to get/set the text value. Similar properties are also provided for the label text, text color , and text box width. No surprise here.

As you look over the code, you'll notice that, with the exception of the text property, all the properties in this custom control use private variables to store their values. These values are lost when the form is rendered and sent to the browser. Because these values are not changed by the user in the browser, there is no need to remember their previous values. The text property is another matter. To provide the ability to remember its previous value, we use the ViewState to persist the value instead of a private variable. We have implemented the LoadPostData method to process the data posted back from the client and set the text property from the postback data.

Notice that we have also implemented the RaisePostDataChangedEvent method. In this first example, the method is empty and not used but is required as part of the IPostBackDataHandler interface. In the recipe's second example, it is used to raise an event when data for the text control changes (more about this later).

A couple of changes from Recipe 5.2s implementation are also required in the Render event. You must set the name and value attributes of the HTML input control. Set the name attribute to a unique identifier so you'll have the ability to obtain the value posted back to the server. If the control does not have a name attribute, the browser will not include its data in the postback data. Set the value attribute to the current text value for the control.

If the text value does not exist, the value attribute should not be output. Absent this check, the value attribute will be output without a value, which is not well- formed HTML and is not handled well by some browsers.


In our second example, we build on the basic structure of the first solely to raise an event if the text in the text box changes and to notify the user with a change in the label text. Because the value that was output when the page was rendered is stored in the ViewState , we can compare it to the new value posted back to the server. As shown in Example 5-10 (VB) and Example 5-11 (C#), if the value changes, the LoadPostData method returns True . Otherwise, it returns False .

When the LoadPostData method returns True , ASP.NET will call the RaisePostDataChangedEvent method after all of the controls have had the opportunity to process their postback data. In this method, we simply raise the OnTextChanged event, passing a reference to the custom control and any event arguments that are applicable , as shown in Example 5-10 (VB) and Example 5-11 (C#). In this example, no arguments are required, so EventArgs.Empty is used for the event arguments parameter.

The event raised in the RaisePostDataChangedEvent must be defined in the custom control class. Further, an event handler in the code-behind of the ASP.NET page hosting the custom control must be "wired" to the event raised by the custom control, as shown here in abridged form (see Example 5-13 and Example 5-14 for the complete listing):

 
figs/vbicon.gif
 Protected WithEvents ccAttributes As CustomControlStateVB2 .. Private Sub ccAttributes_OnTextChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles ccAttributes.OnTextChanged labMessage.Text = "Data Changed" End Sub 'ccAttributes_OnTextChanged 
figs/csharpicon.gif
 protected CustomControlStateCS2 ccAttributes; .. private void Page_Load(object sender, System.EventArgs e) { // wire the event to the text changed event of the custom control ccAttributes.OnTextChanged += new EventHandler(this.ccAttributes_OnTextChanged); } // Page_Load .. public void ccAttributes_OnTextChanged(System.Object sender, EventArgs e) { // update the label with the message in the event arguments labMessage.Text = "Data Changed"; } // ccAttributes_OnTextChanged 

5.3.4 See Also

Recipe 5.2

Example 5-7. Custom control with state (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH05CustomControlWithStateVB1.vb ' ' Description: This class provides a custom control that maintains state ' through postbacks to the server. ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Collections.Specialized Imports System.Drawing Imports System.Web Imports System.Web.UI Namespace ASPNetCookbook.VBExamples Public Class CH05CustomControlWithStateVB1 Inherits Control  Implements IPostBackDataHandler  'private copies of attribute data Private mLabelText As String = "Label: " Private mTextColor As Color = Color.Black Private mTextboxWidth As Integer = 3 '************************************************************************* ' ' ROUTINE: labelText ' ' DESCRIPTION: This property provides the ability to set the text of ' of the label in the control. '------------------------------------------------------------------------- Public Property labelText( ) As String Get Return (mLabelText) End Get Set(ByVal Value As String) mLabelText = Value End Set End Property '************************************************************************* ' ' ROUTINE: textColor ' ' DESCRIPTION: This property provides the ability to set the color ' of the text in the control. '------------------------------------------------------------------------- Public Property textColor( ) As Color Get Return (mTextColor) End Get Set(ByVal Value As Color) mTextColor = Value End Set End Property 'textColor '************************************************************************* ' ' ROUTINE: textboxWidth ' ' DESCRIPTION: This property provides the ability to set the width ' of the textbox in the control. '------------------------------------------------------------------------- Public Property textboxWidth( ) As Integer Get Return (mTextboxWidth) End Get Set(ByVal Value As Integer) mTextboxWidth = Value End Set End Property 'textboxWidth '************************************************************************* ' ' ROUTINE: text ' ' DESCRIPTION: This property provides the ability to set the text ' in the textbox in the control. NOTE: The text value ' is stored in the ViewState instead of a private variable ' to provide the ability to check the current and previous ' values to determine if the text has changed. '-------------------------------------------------------------------------  Const VS_TEXTBOX_VALUE As String = "TextboxValue"   Public Property text( ) As String   Get   Dim value As String = Nothing   If (Not IsNothing(viewstate(VS_TEXTBOX_VALUE))) Then   value = CStr(viewstate(VS_TEXTBOX_VALUE))   End If   Return (value)   End Get   Set(ByVal Value As String)   viewstate(VS_TEXTBOX_VALUE) = Value   End Set   End Property 'text  '************************************************************************* ' ' ROUTINE: Render ' ' DESCRIPTION: This routine renders the HTML output of the control. '------------------------------------------------------------------------- Protected Overrides Sub Render(ByVal writer As HtmlTextWriter) 'output label within a font tag writer.AddAttribute("color", _ ColorTranslator.ToHtml(textColor)) writer.RenderBeginTag(HtmlTextWriterTag.Font) writer.Write(labelText) writer.RenderEndTag( ) 'output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, _ "text") writer.AddAttribute(HtmlTextWriterAttribute.Size, _ textboxWidth.ToString( ))  'output name attribute to identify data on postback   writer.AddAttribute(HtmlTextWriterAttribute.Name, _   Me.UniqueID)   'output value attribute only if value exists   If (Not IsNothing(text)) Then   writer.AddAttribute(HtmlTextWriterAttribute.Value, _   text)   End If  writer.RenderBeginTag(HtmlTextWriterTag.Input) writer.RenderEndTag( ) End Sub 'Render '************************************************************************* ' ' ROUTINE: LoadPostData ' ' DESCRIPTION: This routine processes data posted back from the client. '-------------------------------------------------------------------------  Public Overridable Function LoadPostData(ByVal postDataKey As String, _   ByVal postCollection As NameValueCollection) As Boolean _   Implements IPostBackDataHandler.LoadPostData   'set the value of the text property from the postback data   text = postCollection(postDataKey)   Return (False)   End Function 'LoadPostData  '************************************************************************* ' ' ROUTINE: RaisePostDataChangedEvent ' ' DESCRIPTION: This routine processes data changed events as a result ' of the postback. '-------------------------------------------------------------------------  Public Overridable Sub RaisePostDataChangedEvent( ) _   Implements IPostBackDataHandler.RaisePostDataChangedEvent   End Sub 'RaisePostDataChangedEvent  End Class 'CH05CustomControlWithStateVB1 End Namespace 

Example 5-8. Custom control with state (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH05CustomControlWithStateCS1 // // Description: This class provides a custom control with attributes to // provide the ability to alter the control programmically. // //**************************************************************************** using System; using System.Collections.Specialized; using System.Drawing; using System.Web; using System.Web.UI; namespace ASPNetCookbook.CSExamples { public class CH05CustomControlWithStateCS1 : Control,  IPostBackDataHandler  { // private copies of attribute data private String mLabelText = "Label: "; private Color mTextColor = Color.Black; private int mTextboxWidth = 3; //************************************************************************ // // ROUTINE: labelText // // DESCRIPTION: This property provides the ability to set the text // of the label in the control. //------------------------------------------------------------------------ public String labelText { get { return(mLabelText); } set { mLabelText = value; } } // labelText //************************************************************************ // // ROUTINE: textColor // // DESCRIPTION: This property provides the ability to get/set the color // of the text in the control. //------------------------------------------------------------------------ public Color textColor { get { return(mTextColor); } set { mTextColor = value; } } // textColor //************************************************************************ // // ROUTINE: textboxWidth // // DESCRIPTION: This property provides the ability to get/set the width // of the textbox in the control. //------------------------------------------------------------------------ public int textboxWidth { get { return(mTextboxWidth); } set { mTextboxWidth = value; } } // textboxWidth //************************************************************************ // // ROUTINE: text // // DESCRIPTION: This property provides the ability to get/set the text // in the textbox in the control. //------------------------------------------------------------------------  const String VS_TEXTBOX_VALUE = "TextboxValue";   public String text   {   get   {   String value = null;   if (ViewState[VS_TEXTBOX_VALUE] != null)   {   value = (String)(ViewState[VS_TEXTBOX_VALUE]);   }   return (value);   }   set   {   ViewState[VS_TEXTBOX_VALUE] = value;   }   } // text  //************************************************************************ // // ROUTINE: Render // // DESCRIPTION: This routine renders the HTML output of the control. //------------------------------------------------------------------------ protected override void Render(HtmlTextWriter writer) { //output label writer.AddAttribute("color", ColorTranslator.ToHtml(textColor)); writer.RenderBeginTag(HtmlTextWriterTag.Font); writer.Write(labelText); writer.RenderEndTag( ); //output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Size, textboxWidth.ToString( ));  // output name attribute to identify data on postback   writer.AddAttribute(HtmlTextWriterAttribute.Name,   this.UniqueID);   // output value attribute only if value exists   if (text != null)   {   writer.AddAttribute(HtmlTextWriterAttribute.Value,   text);   }  writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag( ); } // Render //************************************************************************ // // ROUTINE: LoadPostData // // DESCRIPTION: This routine processes data posted back from the client. //------------------------------------------------------------------------  public virtual bool LoadPostData(string postDataKey,   NameValueCollection postCollection)   {   // set the value of the text property from the postback data   text = postCollection[postDataKey];   return (false);   } // LoadPostData  //************************************************************************ // // ROUTINE: RaisePostDataChangedEvent // // DESCRIPTION: This routine processes data changed events as a result // of the postback. //------------------------------------------------------------------------  public virtual void RaisePostDataChangedEvent( )   {   } // RaisePostDataChangedEvent  } // CH05CustomControlWithStateCS1 } 

Example 5-9. Using the custom control with state (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH05DisplayControlWithStateVB1.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH05DisplayControlWithStateVB1" %>  <%@ Register TagPrefix="ASPCookbook" Namespace="ASPNetCookbook.VBExamples"   Assembly="ASPNetCookbookVB" %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Custom Control With State</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmCustomControl" method="post" runat ="server"> <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Custom Control With State (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr bgcolor ="#ffffcc"> <td align="center">  <ASPCookbook:CH05CustomControlWithStateVB1   id="ccAttributes" runat="server"   labelText="Enter Age: "   textColor="#000080"   textboxWidth="5" />  </td> </tr> <tr> <td align="center"> <br> <asp:ImageButton ID="btnSubmit" Runat="server" ImageUrl="images/ buttons /button_submit.gif" /> </td> </tr> </table> </form> </body> </html> 

Example 5-10. Custom control with state and changed event (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH05CustomControlWithStateVB2.vb ' ' Description: This class provides a custom control that maintains state ' through postbacks to the server and raises an event when ' the entered data changes. ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Collections.Specialized Imports System.Drawing Imports System.Web Imports System.Web.UI Namespace ASPNetCookbook.VBExamples Public Class CH05CustomControlWithStateVB2 Inherits Control Implements IPostBackDataHandler  'define an event to be raised if the text changes   Public Event OnTextChanged As EventHandler  'private copies of attribute data Private mLabelText As String = "Label: " Private mTextColor As Color = Color.Black Private mTextboxWidth As Integer = 3 '************************************************************************* ' ' ROUTINE: labelText ' ' DESCRIPTION: This property provides the ability to set the text of ' of the label in the control. '------------------------------------------------------------------------- Public Property labelText( ) As String Get Return (mLabelText) End Get Set(ByVal Value As String) mLabelText = Value End Set End Property '************************************************************************* ' ' ROUTINE: textColor ' ' DESCRIPTION: This property provides the ability to set the color ' of the text in the control. '------------------------------------------------------------------------- Public Property textColor( ) As Color Get Return (mTextColor) End Get Set(ByVal Value As Color) mTextColor = Value End Set End Property 'textColor '************************************************************************* ' ' ROUTINE: textboxWidth ' ' DESCRIPTION: This property provides the ability to set the width ' of the textbox in the control. '------------------------------------------------------------------------- Public Property textboxWidth( ) As Integer Get Return (mTextboxWidth) End Get Set(ByVal Value As Integer) mTextboxWidth = Value End Set End Property 'textboxWidth '************************************************************************* ' ' ROUTINE: text ' ' DESCRIPTION: This property provides the ability to set the text ' in the textbox in the control. NOTE: The text value ' is stored in the ViewState instead of a private variable ' to provide the ability to check the current and previous ' values to determine if the text has changed. '------------------------------------------------------------------------- Const VS_TEXTBOX_VALUE As String = "TextboxValue" Public Property text( ) As String Get Dim value As String = Nothing If (Not IsNothing(viewstate(VS_TEXTBOX_VALUE))) Then value = CStr(viewstate(VS_TEXTBOX_VALUE)) End If Return (value) End Get Set(ByVal Value As String) viewstate(VS_TEXTBOX_VALUE) = Value End Set End Property 'text '************************************************************************* ' ' ROUTINE: Render ' ' DESCRIPTION: This routine renders the HTML output of the control. '------------------------------------------------------------------------- Protected Overrides Sub Render(ByVal writer As HtmlTextWriter) 'output label within a font tag writer.AddAttribute("color", _ ColorTranslator.ToHtml(textColor)) writer.RenderBeginTag(HtmlTextWriterTag.Font) writer.Write(labelText) writer.RenderEndTag( ) 'output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, _ "text") writer.AddAttribute(HtmlTextWriterAttribute.Size, _ textboxWidth.ToString( )) 'output name attribute to identify data on postback writer.AddAttribute(HtmlTextWriterAttribute.Name, _ Me.UniqueID) 'output value attribute only if value exists If (Not IsNothing(text)) Then writer.AddAttribute(HtmlTextWriterAttribute.Value, _ text) End If writer.RenderBeginTag(HtmlTextWriterTag.Input) writer.RenderEndTag( ) End Sub 'Render '************************************************************************* ' ' ROUTINE: LoadPostData ' ' DESCRIPTION: This routine processes data posted back from the client. '-------------------------------------------------------------------------  Public Overridable Function LoadPostData(ByVal postDataKey As String, _   ByVal postCollection As NameValueCollection) As Boolean _   Implements IPostBackDataHandler.LoadPostData   Dim dataChanged As Boolean = False   Dim postbackValue As String   'check to see if the data changed   postbackValue = postCollection(postDataKey)   If (Not postbackValue.Equals(text)) Then   dataChanged = True   End If   'set the value of the text property from the postback data   text = postbackValue   Return (dataChanged)   End Function 'LoadPostData  '************************************************************************* ' ' ROUTINE: RaisePostDataChangedEvent ' ' DESCRIPTION: This routine processes data changed events as a result ' of the postback. '-------------------------------------------------------------------------  Public Overridable Sub RaisePostDataChangedEvent( ) _   Implements IPostBackDataHandler.RaisePostDataChangedEvent   RaiseEvent OnTextChanged(Me, EventArgs.Empty)   End Sub 'RaisePostDataChangedEvent  End Class 'CH05CustomControlWithStateVB2 End Namespace 

Example 5-11. Custom control with state and changed event (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH05CustomControlWithStateCS2 // // Description: This class provides a custom control that maintains state // through postbacks to the server and raises an event when // the entered data changes. // //**************************************************************************** using System; using System.Collections.Specialized; using System.Drawing; using System.Web; using System.Web.UI; namespace ASPNetCookbook.CSExamples { public class CH05CustomControlWithStateCS2 : Control, IPostBackDataHandler {  // define an event to be raised if the text changes   public event EventHandler OnTextChanged;  // private copies of attribute data private String mLabelText = "Label: "; private Color mTextColor = Color.Black; private int mTextboxWidth = 3; //************************************************************************ // // ROUTINE: labelText // // DESCRIPTION: This property provides the ability to set the text // of the label in the control. //------------------------------------------------------------------------ public String labelText { get { return(mLabelText); } set { mLabelText = value; } } // labelText //************************************************************************ // // ROUTINE: textColor // // DESCRIPTION: This property provides the ability to get/set the color // of the text in the control. //------------------------------------------------------------------------ public Color textColor { get { return(mTextColor); } set { mTextColor = value; } } // textColor //************************************************************************ // // ROUTINE: textboxWidth // // DESCRIPTION: This property provides the ability to get/set the width // of the textbox in the control. //------------------------------------------------------------------------ public int textboxWidth { get { return(mTextboxWidth); } set { mTextboxWidth = value; } } // textboxWidth //************************************************************************ // // ROUTINE: text // // DESCRIPTION: This property provides the ability to get/set the text // in the textbox in the control. //------------------------------------------------------------------------ const String VS_TEXTBOX_VALUE = "TextboxValue"; public String text { get { String value = null; if (ViewState[VS_TEXTBOX_VALUE] != null) { value = (String)(ViewState[VS_TEXTBOX_VALUE]); } return (value); } set { ViewState[VS_TEXTBOX_VALUE] = value; } } // text //************************************************************************ // // ROUTINE: Render // // DESCRIPTION: This routine renders the HTML output of the control. //------------------------------------------------------------------------ protected override void Render(HtmlTextWriter writer) { //output label writer.AddAttribute("color", ColorTranslator.ToHtml(textColor)); writer.RenderBeginTag(HtmlTextWriterTag.Font); writer.Write(labelText); writer.RenderEndTag( ); //output input control writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Size, textboxWidth.ToString( )); // output name attribute to identify data on postback writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); // output value attribute only if value exists if (text != null) { writer.AddAttribute(HtmlTextWriterAttribute.Value, text); } writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag( ); } // Render //************************************************************************ // // ROUTINE: LoadPostData // // DESCRIPTION: This routine processes data posted back from the client. //------------------------------------------------------------------------  public virtual bool LoadPostData(string postDataKey,   NameValueCollection postCollection)   {   bool dataChanged = false;   String postbackValue;   // check to see if the data changed   postbackValue = postCollection[postDataKey];   if (!postbackValue.Equals(text))   {   dataChanged = true;   }   // set the value of the text property from the postback data   text = postbackValue;   return (dataChanged);   } // LoadPostData  //************************************************************************ // // ROUTINE: RaisePostDataChangedEvent // // DESCRIPTION: This routine processes data changed events as a result // of the postback. // //------------------------------------------------------------------------  public virtual void RaisePostDataChangedEvent( )   {   // raise event if a handler is assigned   if (OnTextChanged != null)   {   OnTextChanged(this, EventArgs.Empty);   }   } // RaisePostDataChangedEvent  } // CH05CustomControlWithStateCS2 } 

Example 5-12. Using the custom control with state and changed event (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH05DisplayControlWithStateVB2. aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH05DisplayControlWithStateVB2" %>  <%@ Register TagPrefix="ASPCookbook" Namespace="ASPNetCookbook.VBExamples"   Assembly="ASPNetCookbookVB" %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Custom Control With State</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmCustomControl" method="post" runat="server"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Custom Control With State And Events (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr bgcolor="#ffffcc"> <td align="center">  <ASPCookbook:CH05CustomControlWithStateVB2   id="ccAttributes" runat="server"   labelText="Enter Age: "   textColor="#000080"   textboxWidth="5" />  </td> </tr> <tr> <td align="center"> <asp:Label ID="labMessage" Runat="server" /> </td> </tr> <tr> <td align="center"> <br> <asp:ImageButton ID="btnSubmit" Runat="server" ImageUrl="images/buttons/button_submit.gif" /> </td> </tr> </table> </form> </body> </html> 

Example 5-13. Using the custom control with state and changed event code-behind (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH05DisplayControlWithStateVB2.aspx.vb ' ' Description: This class provides the code behind for ' CH05DisplayControlWithStateVB2.aspx ' '***************************************************************************** Namespace ASPNetCookbook.VBExamples Public Class CH05DisplayControlWithStateVB2 Inherits System.Web.UI.Page 'controls on the form  Protected WithEvents ccAttributes As CH05CustomControlWithStateVB2  Protected labMessage As System.Web.UI.WebControls.Label '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load labMessage.Text = "" End Sub 'Page_Load '************************************************************************* ' ' ROUTINE: ccAttributes_OnTextChanged ' ' DESCRIPTION: This routine provides the event handler for the custom ' control text changed event. '-------------------------------------------------------------------------  Private Sub ccAttributes_OnTextChanged(ByVal sender As Object, _   ByVal e As System.EventArgs) _   Handles ccAttributes.OnTextChanged   labMessage.Text = "Data Changed"   End Sub 'ccAttributes_OnTextChanged  End Class 'CH05DisplayControlWithStateVB2 End Namespace 

Example 5-14. Using the custom control with state and changed event code-behind (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH05DisplayControlWithStateCS2.ascx.cs // // Description: This module provides the code behind for // CH05DisplayControlWithStateCS2.ascx // //**************************************************************************** using System; namespace ASPNetCookbook.CSExamples { public class CH05DisplayControlWithStateCS2 : System.Web.UI.Page { // controls on the form protected CH05CustomControlWithStateCS2 ccAttributes; protected System.Web.UI.WebControls.Label labMessage; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) {  // wire the event to the text changed event of the custom control   ccAttributes.OnTextChanged +=   new EventHandler(this.ccAttributes_OnTextChanged);  labMessage.Text = ""; } // Page_Load //************************************************************************ // // ROUTINE: ccAttributes_OnTextChanged // // DESCRIPTION: This routine provides the event handler that is the // recipient of the event raised custom control. //------------------------------------------------------------------------  public void ccAttributes_OnTextChanged(System.Object sender,   EventArgs e)   {   // update the label with the message in the event arguments   labMessage.Text = "Data Changed";   } // ccAttributes_OnTextChanged  } // CH05DisplayControlWithStateCS2 } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2006
Pages: 179

Similar book on Amazon

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