ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

ImageButtons don't have a click() event!  The ImageButton isn't like a regular Html Button.  The ImageButton isn't like a regular Html Button. They work by using the <INPUT type=image... tag, which was used for imagemaps. They intrinsically send x & y coords of where the image was clicked, and otherwise behave as a submit button, causing a post immediately (to be consumed by imagemapper cgis)

Anyway, if you want to trigger a post when your user clicks Enter while focused on a textbox, you need to somehow trap the event without having a html button's click() event to fire.

I highly recommend creating a base page from which to inherit all pages in your web app.

Usage:

1. Create a base page (or user control) to inherit from.
2. For all pages in application, inherit from this base page instead of System.Web.UI.Page or System.Web.UI.UserControl
3. Copy the 3 methods below into the base page (don't change anything).

Set focus to a control when form loads:
In Page_Load, add: base.SetFocus(this.txtControl);

Set Textbox OnEnter to trigger Button's click() event:
In Page_Load, add: base.TieButton(this.txtControl, btnGo);

Set OnEnter for a standalone Textbox, or Textbox with ImageButton:
1. In IDE, double-click textbox to create _TextChanged event handler.  Handle postback here.
2. In Page_Load, add: base.SetOnEnter(txtControl);

private void Page_Load(object sender, System.EventArgs e) {
      AddEnterPressedScriptBlock();
}

private void AddEnterPressedScriptBlock(){
      string jsString="<script language=javascript><!--function EnterPressed(){"+
            "if((event.which && event.which==13)||(event.keyCode && event.keyCode==13))"+
            "return true;"+
            "return false;}"+
            "--></script>
";
      Page.RegisterClientScriptBlock("EnterPressed",jsString);
}

protected void SetFocus(Control controlToFocus){
      string formName = GetFormName(controlToFocus);
      string jsString="<script language=javascript>document." + formName + ".elements['" + controlToFocus.UniqueID + "'].focus();</script>";
      if(Page.IsStartupScriptRegistered("SetFocusToSearch")==false)
            Page.RegisterStartupScript("SetFocusToSearch",jsString);
}

protected void SetOnEnter(Control TextBoxToSet){
      string formName = GetFormName(TextBoxToSet);
      string jsString = "if(EnterPressed()){"+
            "__doPostBack('"+TextBoxToSet.UniqueID+"','');}";
      
if (TextBoxToSet is System.Web.UI.HtmlControls.HtmlControl)
            ((System.Web.UI.HtmlControls.HtmlControl)TextBoxToSet).Attributes.Add("onkeydown",jsString);
      else if (TextBoxToSet is System.Web.UI.WebControls.WebControl)
            ((System.Web.UI.WebControls.WebControl)TextBoxToSet).Attributes.Add("onkeydown",jsString);
      else { // We throw an exception if TextBoxToSet is not of type HtmlControl or WebControl.
            throw new ArgumentException("Control TextBoxToSet should be derived from either System.Web.UI.HtmlControls.HtmlControl or System.Web.UI.WebControls.WebControl", "TextBoxToSet");
      }
}

protected void TieButton(Control TextBoxToTie, Control ButtonToTie){
      string formName = GetFormName(ButtonToTie);
      string jsString = "if(EnterPressed()){"+
            "document."+formName+".elements['"+ButtonToTie.UniqueID+"'].click();}";
      if (TextBoxToTie is System.Web.UI.HtmlControls.HtmlControl)
            ((System.Web.UI.HtmlControls.HtmlControl)TextBoxToTie).Attributes.Add("onkeydown",jsString);
      else if (TextBoxToTie is System.Web.UI.WebControls.WebControl)
            ((System.Web.UI.WebControls.WebControl)TextBoxToTie).Attributes.Add("onkeydown",jsString);
      else { // We throw an exception if TextBoxToTie is not of type HtmlControl or WebControl.
            throw new ArgumentException("Control TextBoxToTie should be derived from either System.Web.UI.HtmlControls.HtmlControl or System.Web.UI.WebControls.WebControl", "TextBoxToTie");
      }
}

protected string GetFormName(Control sourceControl){
      string formName;
      try{
            int i=0;
            Control c = sourceControl.Parent;
            while(! (c is System.Web.UI.HtmlControls.HtmlForm) &! (c is System.Web.UI.Page) && i<500){
                  c = c.Parent;
                  i++;
            }
            if(c is System.Web.UI.HtmlControls.HtmlForm)
                  formName=c.ClientID;
            else
                  formName="forms(0)";
      }
      catch{formName="forms(0)";}
      return formName;
}

Notes:

I previously did a VB.Net version here, without the SetOnEnter method.

Scott Hanselman has a post here with many other options.  This one has worked beautifully for me.

Print | posted on Tuesday, May 24, 2005 1:19 PM

Feedback

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by OldCom at 6/29/2005 11:06 PM Gravatar
so cool...

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by sudath at 7/6/2005 5:33 PM Gravatar
Great stuff. Good job. this helped me a lot

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by Satish Bembalore at 7/15/2005 9:48 AM Gravatar
Thanks a lot. Nice bit of code, which I desperatly wanted.

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by Ganesh at 8/18/2005 3:16 PM Gravatar
Excellent code....very good approach for setting client side script

Regards
Ganesh

ganesh_ha@yahoo.co.in

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by Selva at 9/29/2005 7:32 AM Gravatar
How to apply this functions?.... Can you tell me

# re: ASP.Net Set Textbox Focus on Page Load and ImageButton OnEnter (C#)

left by Selvakumar at 9/29/2005 9:15 AM Gravatar
Guys,

How to apply for textboxes and buttons.. and other objects.. Please give me an example for apply.

Thanks in Advance.


regards,

Selvakumar.B
Title  
Name
Email (never displayed)
Url
Comments   
Please add 1 and 4 and type the answer here: