Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET
Article

XTextBox - Extended Textbox with EnterKey Event Handler

Rate me:
Please Sign up or sign in to vote.
3.89/5 (5 votes)
3 May 20072 min read 64.9K   931   28   5
An extended textbox with Enter key event handler.

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

JavaScript
<script language='javascript'> 

<!-- 
function __doThis(fld){ 
    var key = window.event.keyCode;
    if(key == 13){
        __doARPostBack(fld.id,'enterkey_event');
        return false;
    } 
    return true;
}
// --> 
</script>

__doARPostBack Function

JavaScript
<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.

C#
protected override void 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.

C#
protected override void 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:

C#
public delegate void KeyDownHandler(Object sender , KeyEventArgs e);

and

C#
public event 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:

  1. Start a new C# Class Library Project ARLib.
  2. Add a class to it called EXTextBox.
  3. Paste the code below to the EXTextBox.cs file:
    C#
    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
    {
    
        public delegate void KeyDownHandler(Object sender , KeyEventArgs e);
        /// <summary>
        /// Summary description for TextBox.
        /// </summary>
    
        public class EXTextBox:System.Web.UI.WebControls.TextBox,
                                            IPostBackDataHandler
        {
            #region Declarations
            //private int maxLength=200;
            public event KeyDownHandler EnterKey; 
            #endregion
    
    #region Overriden Functions
            protected override void 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);
            }
    
    protected override void OnPreRender(EventArgs e)
            {
                if (this.EnterKey != null)
                {
                    this.Attributes.Add("onkeydown","return __doThis(this);");
                }
                
                base.OnPreRender(e);
            }
    
    #endregion
    #region EventHandler
            protected virtual void OnEnterKey(KeyEventArgs e)
            {
                if(this.EnterKey != null)
                this.EnterKey(this , e);
            }
    #endregion
        
    #region IPostBackDataHandler Members
        
            public void RaisePostDataChangedEvent()
            {
                // Do Nothing
            }
    
            public bool 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; 
                    }
                }
                return false;
            }
    #endregion
    #region Properties
    #endregion
    }
    
    #region KeyEventArgs Class
        public class KeyEventArgs:System.EventArgs
        { 
            private string textBoxID;
            private string text;
            public KeyEventArgs()
            { 
            }
            public string TextBoxID
            {
                set
                {
                    this.textBoxID = value;
                }
                get
                {
                    return this.textBoxID;
                }
            }
            public string Text
            {
                set
                {
                    this.text = value;
                }
                get
                {
                    return this.text;
                }
            }
        }
    #endregion
    }
  4. Compile the library.
  5. Start a new Web Project and add a Web Form to it.
  6. Right click the toolbox and select Add/Remove Items and select the DLL ARLib.
  7. Add an instance of this to the Web Form. Then add the event handler for the EnterKey event as:
    C#
    this.EXTextBox1.EnterKey += new ARLib.KeyDownHandler(
        this.EXTextBox_EnterKey);
    private void 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...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Russell Aboobacker is a Software Engineer from India, Currently working in Cognizant, Bangalore as Software Architect. He Enjoys Coding and Sharing his Experiences with the Colleagues and Friends.When he is not coding he enjoys spending time with his Family.

If you have any suggestions / Ideas , Share it With me. arusselkm@yahoo.com

Comments and Discussions

 
GeneralHacked !! Pin
zecompadre4-May-07 1:23
zecompadre4-May-07 1:23 
QuestionDefaultButton? Pin
miies3-May-07 12:19
miies3-May-07 12:19 
Hi, do you know about <asp:Panel DefaultButton="btnSubmit"> ? Seems to me like you're re-inventing the wheel..

AnswerRe: DefaultButton? Pin
Russell Aboobacker3-May-07 18:37
Russell Aboobacker3-May-07 18:37 
GeneralRe: DefaultButton? Pin
miies3-May-07 20:29
miies3-May-07 20:29 
GeneralImplementation problems Pin
Robert van Poelgeest20-Sep-05 9:04
Robert van Poelgeest20-Sep-05 9:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.