Mega Code Archive

 
Categories / ASP.Net Tutorial / Custom Controls
 

Processing Postback Data and Events

using System; using System.Web.UI; using System.Web.UI.WebControls; namespace myControls {     public class CustomTextBox : WebControl, IPostBackDataHandler     {         public event EventHandler TextChanged;         public string Text        {             get             {                 if (ViewState["Text"] == null)                     return String.Empty;                 else                     return (string)ViewState["Text"];             }             set { ViewState["Text"] = value; }         }         protected override void AddAttributesToRender(HtmlTextWriter writer)         {             writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");             writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);             writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);             base.AddAttributesToRender(writer);         }         protected override HtmlTextWriterTag TagKey         {             get             {                 return HtmlTextWriterTag.Input;             }         }         public bool LoadPostData(string postDataKey, System.Collections. Specialized.NameValueCollection postCollection)         {             if (postCollection[postDataKey] != Text)             {                 Text = postCollection[postDataKey];                 return true;             }             return false;         }         public void RaisePostDataChangedEvent()         {             if (TextChanged != null)                 TextChanged(this, EventArgs.Empty);         }     } } File: Default.aspx <%@ Page Language="C#" %> <%@ Register TagPrefix="custom" Namespace="myControls" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     protected void CustomTextBox1_TextChanged(object sender, EventArgs e)     {         lblResults.Text = CustomTextBox1.Text;     } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">     <title>Show CustomTextBox</title> </head> <body>     <form id="form1" runat="server">     <div>     <custom:CustomTextBox         id="CustomTextBox1"         OnTextChanged="CustomTextBox1_TextChanged"         Runat="server" />     <asp:Button id="btnSubmit"         Text="Submit"         Runat="server" />     <hr />     <asp:Label         id="lblResults"         Runat="server" />     </div>     </form> </body> </html>