带有EnterKey事件处理程序的XTextBox扩展文本框

分享于 

分钟阅读

 
点击句子查看译文 显示原文      显示译文      双语对照    源址


Introduction

EXTextBox is an extended textbox with an Enter key event handler.that means, you can add an event handler function to be called on the server side while you press the Enter key over the EXTextBox.this idea came to me when i had problem with a page having a number of buttons and textboxes and among it i had a search form in the same page.and as you know most of the users use the Enter key instead of pressing the search button in a search form.and here is the problem, we cannot predict which event is going to be called, since we have a number of buttons in the same page.so i thought it would be better if i have a textbox control that can handle the Enter key.something like"Requirement is the Father of invention"?

As usual i went to the next step, the implementation.for this to work, the textbox should have a client side event which should post the form while you press the Enter key.so i wrote two simple JavaScript functions for it, __doThis and __doARPostBack.

__doThis Function
<script language="'javascript'"> 
<!-- function __doThis(fld){ 
 var key = window.event.keyCode;
 if(key == 13){
 __doARPostBack(fld.id,'enterkey_event');
 returnfalse;
 } 
 returntrue;
}// --> </script>
__doARPostBack Function
<script language="'javascript'">
<!--function __doARPostBack(eventTarget, eventArgument) {
 var theform;
 if (window.navigator.appName.toLowerCase().indexOf('netscape')> -1) {
 theform = document.forms[0];
 }
 else {
 theform = document.forms[0];
 }
 ////Set the hidden field values// theform.__EVENTTARGET.value = eventTarget.split('$').join(':');
 theform.__EVENTARGUMENT.value = eventArgument;
 theform.submit();
}// --></script>

The code blocks are registered to the client inside the OnInit function of the TextBox by overriding it.and two hidden fields, __EVENTTARGET and __EVENTARGUMENT are also registered with the page.__EVENTTARGET will carry the ID of the EXTextBox which fired the event, and the __EVENTARGUMENT will carry extra information.

protectedoverridevoid OnInit(EventArgs e)
{
 base.OnInit (e); 
 ////Add the Hidden Fields __EVENTTARGET and __EVENTARGUMENT//this.Page.RegisterHiddenField("__EVENTTARGET","");
 this.Page.RegisterHiddenField("__EVENTARGUMENT","");
 ////Add the Client Side Scripts __doPostBack and __doThis//string strScript = @"<script language="'javascript'">
 <!--
 function __doARPostBack(eventTarget, eventArgument) {
 var theform;
 if (window.navigator.appName.toLowerCase().indexOf(
 'netscape')> -1) {
 theform = document.forms[0];
 }
 else {
 theform = document.forms[0];
 }
//
//Set the hidden field values
//
 theform.__EVENTTARGET.value = eventTarget.split('$').join(':');
 theform.__EVENTARGUMENT.value = eventArgument;
 theform.submit();
 }
//-->
 </script>";
 //if(this.Page.ParseControl)this.Page.RegisterClientScriptBlock("doPost",strScript);
 strScript = @"<script language="'javascript'"> 
 function __doThis(fld){ 
 var key = window.event.keyCode;
 if(key == 13){
 __doARPostBack(fld.id,'enterkey_event');
 return false;
 } 
 return true;
 } 
 </script>";
 this.Page.RegisterClientScriptBlock("doThis",strScript);
}

The next thing is to call the __doThis function on the KeyDown event of the textbox.for this override the Render function of the TextBox.

protectedoverridevoid OnPreRender(EventArgs e)
 {
 if (this.EnterKey!= null)
 {
 this.Attributes.Add("onkeydown","return __doThis(this);");
 }
 base.OnPreRender(e);
 }

Now we should setup a server side event handler to serve our custom event.for that, first of all we have to declare a delegate function :

publicdelegatevoid KeyDownHandler(Object sender, KeyEventArgs e);

and

publicevent KeyDownHandler EnterKey;

Then add a function OnEnterKey which will be called during the event.

Where is the event going to be invoked?when the page is posted back the control can access the postback data if it implements the IPostBackDataHandler interface.this has two functions which are to be implemented, LoadPostData and RaisePostDataChangedEvent.out of this we will use the LoadPostData to access the posted back data.here check the posted back data to get the values of the hidden fields __EVENTTARGET and __EVENTARGUMENT and call the event handler OnEnterKey accordingly.

Let's do the implementation step by step :

  • Start a new C# Class Library Project ARLib.
  • Add a class to it called EXTextBox.
  • Paste the code below to the EXTextBox.cs file:
using System;using System.Web.UI;using System.Web.UI.WebControls;using System.ComponentModel;using System.IO;using System.Reflection;using System.Text;using System.Text.RegularExpressions;namespace ARLib
{
 publicdelegatevoid KeyDownHandler(Object sender, KeyEventArgs e);
 ///<summary>/// Summary description for TextBox.///</summary>publicclass EXTextBox:System.Web.UI.WebControls.TextBox,
 IPostBackDataHandler
 {
 #region Declarations//private int maxLength=200;publicevent KeyDownHandler EnterKey; 
 #endregion#region Overriden Functionsprotectedoverridevoid OnInit(EventArgs e)
 {
 base.OnInit (e);
 ////Add the Hidden Fields __EVENTTARGET and __EVENTARGUMENT//this.Page.RegisterHiddenField("__EVENTTARGET","");
 this.Page.RegisterHiddenField("__EVENTARGUMENT","");
 ////Add the Client Side Scripts __doPostBack and __doThis//string strScript = @"<script language="'javascript'">
 <!--
 function __doARPostBack(eventTarget, eventArgument) {
 var theform;
 if (window.navigator.appName.toLowerCase().
 indexOf('netscape')> -1) {
 theform = document.forms[0];
 }
 else {
 theform = document.forms[0];
 }
//
//Set the hidden field values
//
 theform.__EVENTTARGET.value = 
 eventTarget.split('$').join(':');
 theform.__EVENTARGUMENT.value = eventArgument;
 theform.submit();
 }
//-->
 </script>";
 //if(this.Page.ParseControl)this.Page.RegisterClientScriptBlock("doPost",strScript);
 strScript = @"<script language="'javascript'"> 
 function __doThis(fld){ 
 var key = window.event.keyCode;
 if(key == 13){
 __doARPostBack(fld.id,'enterkey_event');
 return false;
 } 
 return true;
 } 
 </script>";
 this.Page.RegisterClientScriptBlock("doThis",strScript);
 }protectedoverridevoid OnPreRender(EventArgs e)
 {
 if (this.EnterKey!= null)
 {
 this.Attributes.Add("onkeydown","return __doThis(this);");
 }
 base.OnPreRender(e);
 }#endregion#region EventHandlerprotectedvirtualvoid OnEnterKey(KeyEventArgs e)
 {
 if(this.EnterKey!= null)
 this.EnterKey(this, e);
 }#endregion#region IPostBackDataHandler Members 
 publicvoid RaisePostDataChangedEvent()
 {
 // Do Nothing }
 publicbool LoadPostData(string postDataKey, 
 System.Collections.Specialized.NameValueCollection 
 postCollection)
 {
 this.Text = postCollection[postDataKey];
 string et = postCollection["__EVENTTARGET"].Trim();
 string ea = postCollection["__EVENTARGUMENT"].Trim();
 ////Compare the Event Target et with the Controls ID to see//whther this control is posted back//if(et.CompareTo(this.ClientID.Trim())==0 )
 {
 switch(ea)
 {
 case"enterkey_event":
 ////Invoke the EnterKey Event// KeyEventArgs k = new KeyEventArgs();
 k.TextBoxID = this.ID;
 k.Text = postCollection[postDataKey];
 this.OnEnterKey(k);
 break; 
 }
 }
 returnfalse;
 }#endregion#region Properties#endregion}#region KeyEventArgs Classpublicclass KeyEventArgs:System.EventArgs
 { 
 privatestring textBoxID;
 privatestring text;
 public KeyEventArgs()
 { 
 }
 publicstring TextBoxID
 {
 set {
 this.textBoxID = value;
 }
 get {
 returnthis.textBoxID;
 }
 }
 publicstring Text
 {
 set {
 this.text = value;
 }
 get {
 returnthis.text;
 }
 }
 }#endregion}
  • Compile the library.
  • Start a new Web Project and add a Web Form to it.
  • Right click the toolbox and select Add/Remove Items and select the DLL ARLib.
  • Add an instance of this to the Web Form.then add the event handler for the EnterKey event as :
this.EXTextBox1.EnterKey += new ARLib.KeyDownHandler(
 this.EXTextBox_EnterKey);privatevoid EXTextBox_EnterKey(object sender, ARLib.KeyEventArgs e)
{
 Response.Write(e.Text);
}

The KeyEventArgs class provides the Text and ID of the TextBox which raises the event.

Hope this helps you...


ext  文本  TEX  EVE  event  Extend