C++ C++ C# C# ASP.NET Security ASP.NET Security ASM ASM Скачать Скачать Поиск Поиск Хостинг Хостинг  
  Программа для работы с LPT портом...
Язык: .NET — ©Alexey...
  "ASP.NET Atlas" – AJAX в исполнении Micro...
Язык: .NET — ©legigor@mail.ru...
  "Невытесняющая" Многопоточность...
Язык: C/C++ — ©...
  Update World C++: Сборник GPL QT исходников
  Весь сайт целиком можно загрузить по ссылкам из раздела Скачать
Дебетовая карта Home Credit [CPS] RU

 XTextBox - Extended Textbox with EnterKey Event Handler / Custom Controls / ASP. NET

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');
        return false;
    } 
    return true;
}
// --> 
</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.

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.

protected override void Render(System.Web.UI.HtmlTextWriter output)
{
    //
    //Setting the maxlength Attribute
    //
    string maxlength = "";
    if(this.MaxLength == 0)
    {
        maxlength = "";
    }
    else
    {
        maxlength = this.MaxLength.ToString();
    }
    //
    //Seting the id and name attribute
    //If the control is inside a user cotrol
    //give it the id / name accordingly
    //
    string id = "";
    string name = "";
    if(this.Parent.GetType().ToString().CompareTo(
       "System.Web.UI.HtmlControls.HtmlForm")== 0 )
    {
        id = this.ID.ToString();
        name = this.ID.ToString();
    }
    else
    {
        id = this.Parent.ID.ToString() + "_" + this.ID.ToString() ;
        name = this.Parent.ID.ToString() + ":" + this.ID.ToString() ;
    }
    //
    //Keeping the ViewState
    //
    string val = "";
    if(this.EnableViewState)
    {
        val = this.Text;
    }
    else
    {
        val = "";
    }
    //
    //The Script that call the __doThis function
    //The Script is to be generated only if the Textbox 
    //is having an event handler for EnterKey Event
    //

    string script = "";
    if(this.EnterKey != null)
    {
        script = " onkeydown=\"return __doThis(this);\" ";
    }
    else
    {
        script = "";
    }
    string sTextBoxHtml ="";
    switch(this.TextMode)
    {
        case TextBoxMode.SingleLine:
            sTextBoxHtml = "<input type=\"text\" size=\""+
              this.Columns+"\" name=\""+name+"\" id=\""+id+
              "\" value=\""+val+"\" maxlength=\""+
              maxlength+"\" "+script+" >";
            break; 
        case TextBoxMode.MultiLine:
            sTextBoxHtml = "<textarea cols=\""+this.Columns+
              "\" rows=\""+this.Rows+"\" name=\""+name+
              "\" id=\""+id+"\" "+script+" >"+val+
              "</textarea>";
            break;
        case TextBoxMode.Password:
            sTextBoxHtml = "<input type=\"password\" size=\""+
              this.Columns+"\" name=\""+name+"\" id=\""+id+
              "\" value=\""+val+"\" maxlength=\""+maxlength+
              "\" "+script+" >";
            break;
    }
    output.Write(sTextBoxHtml);
}

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:

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

and

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:
    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 Render(System.Web.UI.HtmlTextWriter output)
            {
                //
                //Setting the maxlength Attribute
                //
                string maxlength = "";
                if(this.MaxLength == 0)
                {
                maxlength = "";
                }
                else
                {
                maxlength = this.MaxLength.ToString();
                }
                //
                //Seting the id and name attribute
                //If the control is inside a user cotrol
                //give it the id / name accordingly
                //
                string id = "";
                string name = "";
                if(this.Parent.GetType().ToString().CompareTo(
                   "System.Web.UI.HtmlControls.HtmlForm")== 0 )
                {
                    id = this.ID.ToString();
                    name = this.ID.ToString();
                }
                else
                {
                    id = this.Parent.ID.ToString() + "_" + this.ID.ToString() ;
                    name = this.Parent.ID.ToString() + ":" + this.ID.ToString() ;
                }
                //
                //Keeping the ViewState
                //
                string val = "";
                if(this.EnableViewState)
                {
                    val = this.Text;
                }
                else
                {
                    val = "";
                }
                //
                //The Script that call the __doThis function
                //The Script is to be generated only if the Textbox 
                //is having an event handler for EnterKey Event
                //
                string script = "";
                if(this.EnterKey != null)
                {
                    script = " onkeydown=\"return __doThis(this);\" ";
                }
                else
                {
                    script = "";
                }
                string sTextBoxHtml ="";
                switch(this.TextMode)
                {
                case TextBoxMode.SingleLine:
                    sTextBoxHtml = "<input type=\"text\" size=\""+
                      this.Columns+"\" name=\""+name+"\" id=\""+id+
                      "\" value=\""+val+"\" maxlength=\""+
                      maxlength+"\" "+script+" >";
                    break; 
                case TextBoxMode.MultiLine:
                    sTextBoxHtml = "<textarea cols=\""+this.Columns+
                      "\" rows=\""+this.Rows+"\" name=\""+name+"\" id=\""+
                      id+"\" "+script+" >"+val+"</textarea>";
                    break;
                case TextBoxMode.Password:
                    sTextBoxHtml = "<input type=\"password\" size=\""+
                      this.Columns+"\" name=\""+name+"\" id=\""+id+
                      "\" value=\""+val+"\" maxlength=\""+
                      maxlength+"\" "+script+" >";
                    break;
                }
                output.Write(sTextBoxHtml);
            }
    
    #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:
    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... Please send your comments and suggestions to arusselkm@yahoo.com.




Дебетовая карта Home Credit [CPS] RU