RSS 2.0 Feed
RSS 2.0


Atom 1.0 Feed
Atom 1.0

  Set Focus to an ASP.NET Control 

Setting focus to controls in your ASP.NET application is a part of giving your end users the feel that they have come to expect. Making your web applications act more like Windows applications is a key to success (IMO). While setting focus to controls is a very small part in achieving this, it does get you one step closer to having a polished web application that your users will love to use. It will be taken for granted, but something this small should be since it is expected behavior.

It is an easy task. It is accomplished in esstentially one line of Javascript. Adding common functionality to a utility class will go a long way in making this task even easier from your .NET web applications. The code below shows a static method that can be used to easily set focus to a control.

public static void SetFocus(Control control)
{
    StringBuilder sb = new StringBuilder();
 
    sb.Append("\r\n<script language='JavaScript'>\r\n");
    sb.Append("<!--\r\n"); 
    sb.Append("function SetFocus()\r\n"); 
    sb.Append("{\r\n"); 
    sb.Append("\tdocument.");
 
    Control p = control.Parent;
    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent; 
 
    sb.Append(p.ClientID);
    sb.Append("['"); 
    sb.Append(control.UniqueID); 
    sb.Append("'].focus();\r\n"); 
    sb.Append("}\r\n"); 
    sb.Append("window.onload = SetFocus;\r\n"); 
    sb.Append("// -->\r\n"); 
    sb.Append("</script>");
 
    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
}

The code results in adding Javascript to your page as follows:

<script language='JavaScript'>
<!--
function SetFocus()
{
    document.Form1['TextBox1'].focus();
}
window.onload = SetFocus;
// -->
</script>

But you don't need to care about that because all you need to do to use it is call your static method from your code behind class:

PageUtility.SetFocus(TextBox1);

This will work from post-backs or from the page load.

Edit

I had some problems with the formatting of the code due to some angle brackets (caused most of the code to disappear). All fixed now. Sorry.




                   



Leave a comment below.

Comments

  1. Joel Ross 12/22/2004 5:16 AM
    Gravatar
    This is much simpler than the other solutions that I have seen. I think this would be pretty cool if it was a server control - you could just drop it on the page, and set a property (control ID), then have a higher level method that uses the ID to find the control in the page hierarchy, and does what you've laid out.

    I've considered doing just that. I'll let you know if I do.
  2. Ryan Farley 12/22/2004 7:04 AM
    Gravatar
    That would be nice. I've actually thought of building it into a base page class. Then it would just be a method on the form itself. It would make things really easy to just use something like:

    this.SetFocus(Textbox1);

    Right now I don't do that because I don't want to change the inheritance of all my pages for a site. Maybe when 2.0 is out and we can use the pageBaseType in the config file then I might go that route.
  3. JOEL'S BLOG 12/23/2004 11:21 PM
    Gravatar
  4. Joel's Virtual Desktop 12/23/2004 11:21 PM
    Gravatar
  5. Joel Ross 12/23/2004 11:22 PM
    Gravatar
  6. Jun Jose 1/3/2005 9:48 AM
    Gravatar
    Certainly works! Thanks for the code.
  7. Laura 2/7/2005 9:08 PM
    Gravatar
    Thanks, the code worked perfectly!! :)
  8. Peter Kaluscha 2/16/2005 4:16 AM
    Gravatar
    Thanks for the code, it works great ;-)
  9. Eric D. Nguyen 2/18/2005 8:20 AM
    Gravatar
    Man, it is excellent. I would like to say thanks, man.
  10. Justin Blaske 2/21/2005 6:29 AM
    Gravatar
    Awesome Job, The Code Works Great. I agree about being able to give a web form the feel of a windows form being very important. I translated your code to VB if you dont mind.

    thanks again!


    sub SetFocus(ByVal ctrl As Control)
    Dim sb As New System.Text.StringBuilder("")
    with sb
    .Append("<script language='JavaScript'>")
    .Append("function SetFocus()")
    .Append("{")
    .Append("document.")
    .Append(ctrl.Parent.ID)
    .Append("['")
    .Append(ctrl.UniqueID)
    .Append("'].focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script")
    .Append(">")
    end with
    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
    end sub
  11. InNeedOfHelp 2/26/2005 10:27 AM
    Gravatar
    Excellent work. Thank you for this great solution.
  12. Murray 3/1/2005 7:56 AM
    Gravatar
    Justin Blake's VB translation works in some, but not all, situations. Here's a more literal translation:

    Replace the line:
    .Append(ctrl.Parent.ID)

    With:
    Dim p As Control = ctrl.Parent
    While (Not (p.GetType() Is _
    GetType(System.Web.UI.HtmlControls.HtmlForm)))
    p = p.Parent
    End While
    .Append(p.ClientID)
  13. Ryan Farley 3/1/2005 8:14 AM
    Gravatar
    Murray,

    I had noticed that. You have to make sure you traverse back up the control hierarchy to get to the parent form. In the case where you have layered panels and such the control's parent will not be the form.

    Thanks.
    -Ryan
  14. Dave R 3/1/2005 10:15 AM
    Gravatar
    This only seems to work with an HTML <Input> textbox. I can't get it to work with an ASP control.
  15. Rain dog 3/3/2005 2:47 PM
    Gravatar
    Yeah, I'm apparently to ignorant to get it to work.

    Exactly how do you use this static method?

    I was under the assumption that you could use a static method of a class without instantiating a member of it explicity.
  16. Ryan Farley 3/7/2005 7:50 AM
    Gravatar
    Dave R,

    The method described works with INPUT, SELECT, TEXTAREA, etc HTML tags. Take a look at the emited javascript and that might help. It would not be able to set focus to a UserControl since it is a server control. You need to think of what HTML the control is rendered as, since the javascript used runs client-side, you'll need to consider the client-side state of your control. It could work to put a small 1x1 pixel textbox on your user control and set focus to that.

    -Ryan
  17. Ryan Farley 3/7/2005 7:55 AM
    Gravatar
    Rain Dog,

    Here's an easy way to use this.

    Create a class, copy the code into it. Then just call the Classname.Method() You're right that since the method is static that you do not need to instanciate the class.

    For example, create a class named PageUtility and add the static method to the class. Then to use it you make sure you add a 'using' for the namespace for the class if needed. Add a TextBox and name it TextBox1 then set focus to it like this:

    PageUtility.SetFocus(TextBox1);

    That is it.

    -Ryan
  18. trulypaladin 3/10/2005 8:43 AM
    Gravatar
    Notice one thing, when you set focus to a control, it automatically scroll the control to the bottom of the page. Any idea how to fix this issue?
  19. Paul Lorena 3/11/2005 2:54 PM
    Gravatar
    _I agree with Rain, the solution implementing a class, with the static method is correct.
  20. Shah 3/16/2005 10:15 PM
    Gravatar
    Thanks for the code !! Its really simple n yet usefull!!
  21. Hasa 3/17/2005 1:43 AM
    Gravatar
    Thanks Ryan, Great help
  22. The Formatter 3/22/2005 9:55 AM
    Gravatar
    I must put in my two bits of gratitude - this helped me quickly take care of a nagging problem in my first ever ASP.NET page.

    I feel much better now..........

  23. Jason 3/23/2005 10:52 AM
    Gravatar
    This is a nice little snippet of code to handle the seemingly straightforward issue of setting focus on page load. I tried it and it works...almost. As I've found with every other snippet of JavaScript and ASP.NET code I've found, having smart navigation turned on causes issues on long page loads. I'm working on an app that has a base page and one subclass that inherits from the base page and acts as the web form for all app pages...very much the design pattern seen in many ASP.NET portal implementations like IBuySpy. In any case, individual user controls need to be able to set focus using a snippet like yours but the smart nav seems to override setting the focus by doing its own work after I set the focus. I've only been able to combat this problem by using window.settimeout() to set the focus, but the timeout value can vary significantly depending on the page load or postback time.

    Enough rambling...I just wondered if you have any thoughts or experience working with setting focus (or other client-side event handlers that need to occur at client-side page load time) while smart navigation is turned on. Thanks for a great post on a simple utility method to set focus and I hope I can adapt it to work when smart nav is on.
  24. Sri 3/24/2005 2:07 PM
    Gravatar
    Awesome works fine
  25. JB 3/31/2005 1:11 PM
    Gravatar
    Hey, this code appears to be exactly what I'm looking for but it's not working. I have a server side drop down list that I'm doing a postback on when the user selects from it. On the post back, I populate a second drop down list control, and call SetFocus. When the page is rendered, the focus is on the Window not on the control. I'm running IE 6.

    My thoughts are that puplating the list box might be interrupting the focus. Any ideas on what might be going wrong?
  26. JB 4/1/2005 2:08 PM
    Gravatar
    I resolved my problem. I used code written by Justin Blake and Murray, of course derived from code written by our host, Ryan Farley. Cheers to all of you.

    Public Shared Sub SetFocus(ByVal ctrl As Control)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    .Append("document.forms('form1').")
    '.Append(ctrl.Parent.ID) 'typically this is the form name where the control lives

    While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))
    p = p.Parent
    End While

    '.Append(p.ClientID)
    '.Append("['")
    .Append(ctrl.UniqueID)
    '.Append("'].focus();")
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script")
    .Append(">")
    End With

    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())

  27. JB 4/1/2005 2:08 PM
    Gravatar
    I resolved my problem. I used code written by Justin Blake and Murray, of course derived from code written by our host, Ryan Farley. Cheers to all of you.

    Public Shared Sub SetFocus(ByVal ctrl As Control)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    .Append("document.forms('form1').")
    '.Append(ctrl.Parent.ID) 'typically this is the form name where the control lives

    While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))
    p = p.Parent
    End While

    '.Append(p.ClientID)
    '.Append("['")
    .Append(ctrl.UniqueID)
    '.Append("'].focus();")
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script")
    .Append(">")
    End With

    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())

  28. JB 4/1/2005 2:17 PM
    Gravatar
    Sorry, that post was a fubar. Here is the cleaned up code.

    Note, this code takes a formName as a string and uses that to reference the relevant form or just references the first form loaded.

    Public Shared Sub SetFocus(ByVal ctrl As Control, Byval formName as string)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    If formName.Trim.Empty Then
    .Append("document.forms(0).")
    Else
    .Append("document.forms('" + formName + ").")
    End If

    .Append(ctrl.UniqueID)
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script>")
    End With

    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())

    End Sub

    Also, I have no idea why the code posted by Justin and Murray didn't work for me. If you've got a clue, please share. Thanks.

    JB
  29. JB 4/1/2005 2:22 PM
    Gravatar
    alright, it's April Fools and I feel really stupid now, but this should be corrected

    The line:

    If formName.Trim.Empty Then

    should read

    If formName = String.Empty Then

    Sorry, sheesh I need a vacation.
  30. valli 4/4/2005 11:48 PM
    Gravatar
    Really good work and very useful
  31. MLY 4/15/2005 2:20 AM
    Gravatar
    Compiler Error Message: CS1010: Newline in constant

    Source Error:

    Line 37: sb.Append("window.onload = SetFocus;\r\n");
    Line 38: sb.Append("// -->\r\n");
    Line 39: sb.Append("</script>");

    Line 39 is the source error. Please help.

    If you are interested, here is the sample code. Thanks!
    ---------------------------------------------------------------------------------
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI.WebControls" %>
    <%@ Page Language="C#" Debug="True" %>

    <script language="C#" runat="server">

    public void Page_Load(Object sender, EventArgs e)
    {
    PageUtility.SetFocus(TxtBox1);
    }

    public void Submit_Click(Object sender, EventArgs e)
    {
    Label.Text = "click";
    }

    public class PageUtility
    {
    public static void SetFocus(Control control)
    {
    StringBuilder sb = new StringBuilder();

    sb.Append("\r\n<script language='JavaScript'>\r\n");
    sb.Append("<!--\r\n");
    sb.Append("function SetFocus()\r\n");
    sb.Append("{\r\n");
    sb.Append("\tdocument.");

    Control p = control.Parent;
    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;

    sb.Append(p.ClientID);
    sb.Append("['");
    sb.Append(control.UniqueID);
    sb.Append("'].focus();\r\n");
    sb.Append("}\r\n");
    sb.Append("window.onload = SetFocus;\r\n");
    sb.Append("// -->\r\n");
    sb.Append("</script>");

    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
    }
    }

    </script>
    <html>
    <head>
    </head>
    <body>
    <form runat="server">
    <h3>TextBox Constructor Example </h3>
    <asp:TextBox id=TxtBox1 text="hi there" runat="server"/>
    <asp:Button ID="SubmitButton"
    Text="Submit"
    OnClick="Submit_Click"
    runat="server"/>
    <asp:label id= "Label" runat="server"/>
    </form>
    </body>
    </html>
  32. Kim 4/24/2005 10:07 AM
    Gravatar
    Thank you so much. It took two seconds to implement since all my pages already inherit from a main template!
  33. h8tow8 4/28/2005 8:07 AM
    Gravatar
    awesome, works fine here, dropped it in a vb module and just call it from there :

    module.functioname(controlname)

    all over the show :)
    cheers
  34. Blake 5/6/2005 4:14 AM
    Gravatar
    Yeah nice work buddy, its good to be able to just copy the code in and use it straight out.
  35. Gary 5/12/2005 12:56 PM
    Gravatar
    THANK YOU THANK YOU THANK YOU. A two hour microsoft fix boiled to a two minute fix. You guys rock. I did notice a small typo so thought I would repaste a corrected version. Including the "If formName.Trim.Empty Then" correction.
    FOR VB
    ----------------------------
    Public Shared Sub SetFocus(ByVal ctrl As Control, ByVal formName As String)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    If formName = String.Empty Then
    .Append("document.forms(0).")
    Else
    .Append("document.forms('" + formName + ")'")
    End If

    .Append(ctrl.UniqueID)
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script>")
    End With

    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())

    End Sub
    --------------------------
    Thanks again.
  36. Gary 5/12/2005 1:04 PM
    Gravatar
    OK I'm an idiot. Vacations for everyone.
    .Append("document.forms('" + formName + ")'")
    should be
    .Append("document.forms('" + formName + "').")
  37. Christian 5/18/2005 4:58 AM
    Gravatar
    Hi
    I modified the VB version, sp that it also works from within a usercontrol.

    Public Shared Sub SetFocus(ByVal ctrl As Control, ByVal formName As String)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    If formName = String.Empty Then
    .Append("document.forms(0).")
    Else
    .Append("document.forms('" + formName + "').")
    End If

    .Append(Replace(ctrl.UniqueID, ":", "_"))
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script>")
    End With

    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
    End Sub
  38. Praveen 5/21/2005 3:50 AM
    Gravatar
    Thanx it solved my problem. it great
  39. Praveen 5/21/2005 4:39 AM
    Gravatar
    Thanx it solved my problem. it great
  40. Gerry Heidenreich 5/24/2005 12:03 PM
    Gravatar
    I used a similar method, but also have functionality to
    1. tie a textbox to any button's click() event on Enter
    2. trap Enter from any textbox, no button required (required for ImageButton, since it doesn't have a click() event)

    http://edsid.com/blog/archive/2005/05/24/464.aspx
  41. AM 5/25/2005 12:44 AM
    Gravatar
    Hi,
    How come it doesn't work for me? :( , I am using dreamwaver.
    I appreciate your input.


    <%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" debug="true" %>

    <%@ Import Namespace="System.Web.UI.WebControls" %>
    <%@ Import Namespace="System.Text" %>
    <%@ Import Namespace="System.IO" %>

    <script language="VB" runat="server">

    Sub SetFocus(ByVal ctrl As Control, ByVal formName As String)

    Dim sb As New StringBuilder
    Dim p As Control = ctrl.Parent
    sb.Append("<script language='JavaScript' type='text/javascript'>")
    sb.Append("function SetFocus()")
    sb.Append("{")
    If formName = String.Empty Then
    sb.Append("document.forms(0).")
    Else
    sb.Append("document.forms('" + formName + "').")
    End If

    sb.Append(Replace(ctrl.UniqueID, ":", "_"))
    sb.Append(".focus();")
    sb.Append("}")
    sb.Append("window.onload = SetFocus;")
    sb.Append("")
    sb.Append("</script")
    sb.Append(">")
    ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
    End Sub

    </script>

    <html>
    <head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <form name="Form1" method="post" action="SetFocus.aspx" id="Form1">

    <input name="TextBox1" type="text" id="TextBox1" style="width:296px;Z-INDEX: 101; LEFT: 48px; POSITION: absolute; TOP: 32px" />
    <input name="TextBox2" type="text" id="TextBox2" style="width:296px;Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 64px" />
    <input name="TextBox3" type="text" id="TextBox3" style="width:296px;Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 96px" />

    <input type="submit" name="Button1" value="validate" id="Button1" style="width:184px;Z-INDEX: 104; LEFT: 352px; POSITION: absolute; TOP: 32px" onclick="SetFocus();"/>
    <input type="submit" name="Button2" value="validate" id="Button2" style="width:184px;Z-INDEX: 105; LEFT: 352px; POSITION: absolute; TOP: 64px" />
    <input type="submit" name="Button3" value="validate" id="Button3" style="width:184px;Z-INDEX: 106; LEFT: 352px; POSITION: absolute; TOP: 96px" />
    <input name="TextBox4" type="text" id="TextBox4" style="width:296px;Z-INDEX: 107; LEFT: 48px; POSITION: absolute; TOP: 128px" />
    <span id="Label1" style="height:16px;width:192px;Z-INDEX: 108; LEFT: 352px; POSITION: absolute; TOP: 128px"><- Page_Load will focus here</span>
    </form>
    <script language='JavaScript'>
    <!--
    function SetFocus()
    {
    document.Form1['TextBox4'].focus();
    }
    window.onload = SetFocus;
    // -->
    </script>
    </body>
    </html>
  42. PP (aspemail@yahoo.com) 5/27/2005 9:34 PM
    Gravatar
    When I copy your code in a seperate CS file (code below), it barfs with error

    c:\inetpub\wwwroot\House4Sale\Library\CommonCode.cs(30): The type or namespace name 'Control' could not be found (are you missing a using directive or an assembly reference?)


    // --------------------------------
    // Setting the FOCUS on screen load
    // --------------------------------
    public static void SetFocusOnLoad(Control control)
    {
    //http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
    StringBuilder sb = new StringBuilder();

    sb.Append("\r\n<script language='JavaScript'>\r\n");
    //sb.Append("<!--\r\n");
    sb.Append("function SetFocus()\r\n");
    sb.Append("{\r\n");
    sb.Append("\tdocument.");

    Control p = control.Parent;
    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;

    sb.Append(p.ClientID);
    sb.Append("['");
    sb.Append(control.UniqueID);
    sb.Append("'].focus();\r\n");
    sb.Append("}\r\n");
    sb.Append("window.onload = SetFocus;\r\n");
    sb.Append("// -->\r\n");
    sb.Append("</script>");

    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
    }
  43. Ryan Farley 5/28/2005 8:11 AM
    Gravatar
    PP,

    Add the following using System.Web.UI to your code.

    -Ryan
  44. Debanu 6/8/2005 1:10 AM
    Gravatar
    If you use Panel above code will not work. IF you use only form and text box it will work. Pls send me code where it will work for panel. Because my text box is inside panel and I have to focus on that text box
  45. Willngton 6/20/2005 11:01 AM
    Gravatar
    Is is very good.
    Congratrulations
    I'm puts this in my class JavaScript

    public void SetFocus(System.Web.UI.Control control, System.Web.UI.Page pagina)
    {
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    sb.Append("\r\n<script language='JavaScript'>\r\n");
    sb.Append("<!--\r\n");
    sb.Append("function SetFocus()\r\n");
    sb.Append("{\r\n");
    sb.Append("\tdocument.");

    System.Web.UI.Control p = control.Parent;

    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;

    sb.Append(p.ClientID);
    sb.Append("['");
    sb.Append(control.UniqueID);
    sb.Append("'].focus();\r\n");
    sb.Append("}\r\n");
    sb.Append("window.onload = SetFocus;\r\n");
    sb.Append("// -->\r\n");
    sb.Append("</script>");


    if( !pagina.IsClientScriptBlockRegistered("SetFocus"))
    {
    pagina.RegisterClientScriptBlock("SetFocus", sb.ToString());
    }
    }
  46. Sameer 7/5/2005 7:52 AM
    Gravatar
    I can't understand why peoples are trying so hard for setting focus on an control, as far as asp.net is concerned it provides you built in method....

    If Browswe is client scripting enabled, Then

    C#-- objectName.Focus();
    Visual Basic--- objectName.Focus()

    "objectName" can be any visible webcontrol.

    Or---> set default focus in a page

    <%@ Page Language="C#" %>
    <html>
    <head runat="server">
    <title>MYtest Page</title>
    </head>
    <body>
    <form id="form1" runat="server" defaultfocus="objName" >
    // Server Control Goes Here
    </form>
    </body>
    </html>

  47. Ryan Farley 7/5/2005 8:37 AM
    Gravatar
    Sameer,

    You're missing the point. We all know that in client-side scripting that you can use objectName.focus() (BTW, that's nothing to do with C# or VB.NET). The point is to be able to emit that client-side script from server-side code. So that you can set focus to a control at runtime during a post-back or other server-side event.

    C#/VB.NET/ASP.NET does not not have a "Focus" method for server-controls, such as a TextBox control. That is a scripting method that you would use with an input object - from script, such as client-side javascript.

    The code in the post (and the comments that follow) are to be used from C# or VB.NET to set focus to a client rendered control (ie: a server control such as a TextBox that will render as an input object on the client) from server-side code.

    -Ryan
  48. BobC 7/6/2005 1:58 PM
    Gravatar
    Thanks. This works great to set focus on the current edit item in a DataGrid. I used it to set focus on the second column:

    SetFocus(DataGrid1.Items[DataGrid1.EditItemIndex].Cells[1].Controls[0]);

    This was especially useful in Firefox.
  49. Bender 7/14/2005 8:23 AM
    Gravatar
    Thank You! Thank You! Thank You!
  50. AjinomotoBaby 7/18/2005 11:30 AM
    Gravatar
    Man you're good!

    Thanks. I'll be back to learn more!
  51. Joar Fagerli 7/20/2005 3:56 AM
    Gravatar
    I have a problem...
    I tried the code (rewritten in vb) and it functioned, but my concern was to set focus on the save-button which I had on the bottom of the page.
    When I am typing something in some control on the page the focus on the save-button are lost!
    Pressing the Enter-button now, causes the very first button on the page (an image-button) to be triggered....

    Any solution???

    Joar
  52. Ryan Farley 7/20/2005 7:42 AM
    Gravatar
    Joar,

    If the user types in a field/textbox then the button *will* loose focus since the textbox will now have focus. There's no way to allow the user to type in a textbox and not have the textbox take focus (which obviously removes focus from the button).

    What you really should look at is checking which control caused the postback (my post at http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx might help) and then do the appropriate action.

    Good luck.

    -Ryan
  53. ashok kumar 7/28/2005 8:00 PM
    Gravatar
    Thank You Very Much its working nice


    Bye
    Ashok
  54. Matt 8/5/2005 1:50 AM
    Gravatar
    Cheers, this looks great, but I'm getting the same error as MLY: newline in constant.
    Maybe it's just my complete lack of understanding of .NET at this stage, a different version of the framework, or what I'm not sure.
    Any help greatly appreciated.
    Thanks
    Matt
  55. Pete 8/11/2005 5:56 AM
    Gravatar
    Hi there guys, I have a page and have managed to get the c# version to work, but my address bar will be the second after I set the focus. Has anyone else had this problem?

    Thanks,
    Pete
  56. Wayne 8/16/2005 12:52 PM
    Gravatar
    If you're using ASP.NET 2.0, this piece of code works nicely in the PageLoad

    Dim ctlName As String = Me.Request.Form("__EVENTTARGET")
    If IsPostBack Then SetFocus(ctlName)
  57. shree 8/18/2005 7:09 AM
    Gravatar
    If my textbox is inside a panel then the function dosent work , what are the changes i need to do to the VB fuctioon in order for this to work

    thanks in advance

    shree
  58. Ryan Farley 8/18/2005 9:59 AM
    Gravatar
    Shree,

    I updated the demo (see link in article) to demonstrate that it does work with textboxes in panels. I don't know what your VB code looks like, but the trick in the C# from my post for it to work while in panels is this part:

    Control p = control.Parent;
    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;

    This will go back up the tree of controls to get to the parent form. In the case where the textbox is in a panel, the panel is now the textboxes parent. You want the end result of the emited javascript to give a line like this to reference the control:

    document.Form1['TextBox1'].focus();

    If you don't walk back up the control tree to the form itself, then you'd end up with js like this to reference the control:

    document.Panel1['TextBox1'].focus();

    Which obviously wouldn't work. I believe someone posted a complete VB version that properly walks back up the control tree to the form object, look through for that and add that to your code.

    -Ryan
  59. dale 8/19/2005 11:48 AM
    Gravatar
    i have a web control page to allow user to login. i have trouble to use the method posted above. any suggestions?

    thanks. -dale
  60. Ryan Farley 8/19/2005 11:53 AM
    Gravatar
    dale,

    Suggestions for what specifically?

    If you're attempting to set focus to textbox inside a user control, you'll have to do it one of two ways. First of all, you could just set focus to the textbox inside the usercontrol from the usercontrol itself. Or, you could expose the textbox via a property of the user control so you could get it and set the focus from the page contiaining the user control. Well, that's my guess anyway, I've not tried that but sounds like it should work to me.

    -Ryan
  61. dale 8/19/2005 12:18 PM
    Gravatar
    Ryan,

    Sorry for the confusing. in my web control page i have a text box for user name, which should be focused.

    I put your code (setFocus) in my C#, and script in html of the page design. can not compile. I thought other people may use it in web form.

    my question is how to set focus to the text box in web control page? I could not understand the two ways you mentioned above.

    Thanks. -Dale
  62. dale 8/19/2005 1:08 PM
    Gravatar
    More info: web control page does not have form (i.e. no "form1"), so the jscript posted at the top does not apply here.

    The following is the html version of the page design:

    <DIV style="WIDTH: 992px; POSITION: relative; HEIGHT: 424px" ms_positioning="GridLayout"><asp:label id="Label3" style="Z-INDEX: 103; LEFT: 344px; POSITION: absolute; TOP: 88px" ForeColor="#FF8080"
    runat="server">Please login to access private content</asp:label>

    <asp:textbox id="txtUserName" style="Z-INDEX: 104; LEFT: 448px; POSITION: absolute; TOP: 144px"
    runat="server"></asp:textbox><asp:label id="lblUserName" style="Z-INDEX: 105; LEFT: 280px; POSITION: absolute; TOP: 144px"
    runat="server">Enter email address</asp:label><asp:label id="lblPassword" style="Z-INDEX: 106; LEFT: 280px; POSITION: absolute; TOP: 192px"
    runat="server">Enter password</asp:label><asp:textbox id="txtPassword" style="Z-INDEX: 107; LEFT: 448px; POSITION: absolute; TOP: 192px"
    runat="server" TextMode="Password"></asp:textbox><asp:button id="Button1" style="Z-INDEX: 108; LEFT: 448px; POSITION: absolute; TOP: 240px" runat="server"
    Text="Login"></asp:button>
    <asp:regularexpressionvalidator id="revUsername" style="Z-INDEX: 111; LEFT: 664px; POSITION: absolute; TOP: 144px"
    runat="server" Display="Dynamic" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtUserName"
    ErrorMessage="Enter the email address as : user@domain.com">*</asp:regularexpressionvalidator><asp:requiredfieldvalidator id="rfvUsername" style="Z-INDEX: 112; LEFT: 728px; POSITION: absolute; TOP: 144px"
    runat="server" Display="Dynamic" ControlToValidate="txtUserName" ErrorMessage="Enter the correct user ID"></asp:requiredfieldvalidator><asp:requiredfieldvalidator id="rfvPassword" style="Z-INDEX: 113; LEFT: 728px; POSITION: absolute; TOP: 192px"
    runat="server" Display="Dynamic" ControlToValidate="txtPassword" ErrorMessage="Enter the correct password"></asp:requiredfieldvalidator><asp:validationsummary id="ValidationSummary1" style="Z-INDEX: 114; LEFT: 440px; POSITION: absolute; TOP: 288px"
    Width="364px" runat="server" HeaderText="Please correct the followings:"></asp:validationsummary><asp:label id="lblSuccess" style="Z-INDEX: 115; LEFT: 544px; POSITION: absolute; TOP: 240px"
    runat="server"></asp:label></DIV>
  63. ravindra 9/10/2005 6:53 AM
    Gravatar
    what a great solution. thankx
  64. Sanjeev 9/12/2005 4:05 PM
    Gravatar
    REAL GOOD SOLUTIONS... THANKS TO RYAN
  65. Pansky 9/19/2005 2:46 AM
    Gravatar
    Great stuff - very useful, thanks to Ryan and all those that have contributed changes, udates and ideas.
  66. Darren 9/22/2005 7:43 AM
    Gravatar
    <b> Focus() JS Method with Javascript </b>

    Dale & Ryan:

    I spent a good half day trying to figure out why my default focus JS function wouldnt work with my login user control. This is what i found:

    a) The "name" attribute of a textbox inside of a user control (pon HTML rendering) uses the following format: [UserControl Name] : [Control ID]
    where UserControl Name is the ASPX ID/declaration name in your code behind.

    b) Either javascript doesnt like colons in document.formname.objectname.focus() or the pseudo-smartnav tool im using (smartscroller) has JS conflicts with that particular naming standard. In either case, document.formname.objectname.focus does NOT work with a usercontrol textbox. However, through pure trial and error, this piece of code DOES work:

    document.all('ucLogin1:txtUserName').focus();

    I haven't integrated this into a setFocus() static method yet but it should work for those of us using a login user control we want to set focus to. Or we can just procrastinate enough until ASP.NET 2.0 comes out, at which point we'll have a built-in SetFocus() method and we wont have to worry about all this. =)
  67. Peter Albanese 9/30/2005 2:40 AM
    Gravatar
    'registers this clientside script to use setfocus in javascript

    '<script language='JavaScript'>
    '<!--
    'function SetFocus()
    '{
    ' document.Form1['TextBox1'].focus();
    '}
    'window.onload = SetFocus;
    '// -->
    '</script>

    Public Shared Sub SetFocus(ByVal control As System.Web.UI.Control)

    Dim sb As New System.Text.StringBuilder
    Dim p As Control = control.Parent

    While Not p.GetType Is GetType(System.Web.UI.HtmlControls.HtmlForm)
    'traverse up the parent chain until you get to the html form
    p = p.Parent
    End While

    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    .Append("document." & p.ID & "['" & control.UniqueID & "']")
    .Append(".focus();")
    .Append("}")
    .Append("window.onload = SetFocus;")
    .Append("")
    .Append("</script>")
    End With

    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())


    End Sub
  68. Panso 9/30/2005 6:08 PM
    Gravatar
    "Making your web applications act more like Windows applications"

    you mean hang occasionally and provide unhelpful dialog messages before performing an illegal operation? ;)

    Nice, simple solution.

    Thanks
  69. Ryan Farley 9/30/2005 6:53 PM
    Gravatar
    Panso,

    Hehe. That's funny. Thanks!

    -Ryan
  70. abhi 10/5/2005 9:04 PM
    Gravatar
    Hey,that works dude,thanks!Only thing i had to delete d word pageutility & use it like setfocus(textbox1);
  71. Sachin 10/5/2005 10:19 PM
    Gravatar
    Thanks for ur help,
    I have been serching since 3 days but I have got answer from this

    really thanks
  72. Ian 10/11/2005 3:21 PM
    Gravatar
    Cool utility!

    I'm using it in the TextChanged event handler for a textbox to set focus (after postback) to the next textbox on the page. While it does set focus to the correct textbox, it doesn't have the text "selected" as it would if you just tab'd through the controls on the page. Instead it places the cursor at the beginning of the string.

    Is there a way to have it set focus on a textbox control and also have that control's text be selected?
  73. Wole Ogunremi 10/26/2005 6:18 AM
    Gravatar
    // Dynamic script block to set focus on and select contents
    // of edit control text box.
    // The selected cell depends on which textbox you want to set
    // focus to. In this case I am setting focus on and selecting
    // the contents of the edit textbox in the second cell (index = 1).
    StringBuilder sB = new StringBuilder();
    string strControlID;
    strControlID = this.DataGridResults.Items[e.Item.ItemIndex].Cells[1].Controls[0].UniqueID;
    sB.Append("\n");
    sB.Append("<script language='javascript' type='text/javascript'>\n");
    sB.Append(" <!-- \n");
    sB.Append(" function setFocus(){\n");
    sB.Append(" var el;");
    sB.Append(" el = document.getElementsByName('" + strControlID + "');");
    sB.Append(" el[0].select();\n");
    sB.Append(" }\n");
    sB.Append(" setFocus();\n");
    sB.Append(" --> \n");
    sB.Append("</script>\n");
    sB.Append("\n");

    if(!this.IsStartupScriptRegistered("myScriptBlock1"))
    this.RegisterStartupScript("myScriptBlock1",sB.ToString());
  74. Mahesh 11/4/2005 8:42 PM
    Gravatar
    Really usefull one..Thanks Ryan.
    Mahes,BLR
  75. abhi 11/10/2005 4:49 AM
    Gravatar
    It's gr8 it helps me very much
  76. PaulG 11/27/2005 8:07 AM
    Gravatar
    Great post, great blog and not the first time I've found a solution posted by Ryan that solves a tedious problem.
    Worked first time out the box.

    Great work Ryan.
  77. Darren L 11/30/2005 6:10 AM
    Gravatar
    Great work Ryan! Really!

    I have successfully implemented you example and it works great. However, initially the focus would not work on PostBack. I could not get this code to work on post back if smartNavigation="True" was used in the HTML on the aspx page. Not sure why.
  78. Bikram 12/7/2005 1:10 AM
    Gravatar
    Thanks. The code helped me a lot. But, I m facing a problem when i am trying to set focus on a checkbox in item template of a datagrid. can someone help me?
  79. Anubhav 12/8/2005 2:56 AM
    Gravatar
    I tried it for a Asp:TextBox Control.
    It gives me a JavaScript error saying "Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus."
    Please help.
  80. john 12/9/2005 5:28 AM
    Gravatar
    So will the vb code above work if you have textboxes within system.web.ui.webcontrols.panel?

    I saw that it doesn't, but wanted to verify. If not, how can we still set foucs on a textbox within a panel?

    Thanks,
    John
  81. Ryan Farley 12/9/2005 6:19 AM
    Gravatar
    I've not tested the VB code someone posted to the comments, but the C# code from my post *does* work with TextBoxes in a panel.
  82. dinesh 12/12/2005 12:11 PM
    Gravatar
    this is really use full site,
    tx
  83. Attaullah Sumalani 12/18/2005 8:44 PM
    Gravatar
    MUUUAAAAAHHHHHHH .... thanks guys.. that was something i've been looking for, for such a long time... you guys are the real computer geeks... One Question: I am a Delphi programmer and have recently started my work with C# why is it that I am not feeling comfortable with the database programming.
  84. Rob Hughes 12/28/2005 9:05 PM
    Gravatar
    // works very well - no matter what language
    // I put this in a BasePage type and inherit all pages
    // in my site from BasePage.
    // tested in IE and Firefox - same result
    // Ryan, you da man.

    procedure TBasePage.SetFocus(AControl: Control);
    var
    SB: StringBuilder;
    P: Control;
    begin
    SB := StringBuilder.Create;

    SB.Append('<script language=''JavaScript''>');
    SB.Append('<!-- ' + #10);
    SB.Append('function SetFocus()');
    SB.Append('{' + #10);
    SB.Append('document.');

    P := AControl.Parent;
    while not(P is System.Web.UI.HtmlControls.HtmlForm) do P := P.Parent;

    SB.Append(P.ClientID);
    SB.Append('[''');
    SB.Append(AControl.UniqueID);
    SB.Append('''].focus();');
    SB.Append(#10 + '}');
    SB.Append(#10 + ' window.onload = SetFocus;');
    SB.Append(' // -->');
    SB.Append('</script>');

    AControl.Page.RegisterClientScriptBlock('SetFocus', SB.ToString());
    end;
  85. WOLF 1/10/2006 11:29 AM
    Gravatar
    Private Sub setFocus(ByVal control As Control)
    Dim strScript As String
    strScript = " <SCRIPT Languaje='Javascript'>" & vbCrLf
    strScript &= " window.attachEvent('onload',function(){document.getElementById('" & control.ClientID & "').focus()}); " & vbCrLf
    strScript &= " </SCRIPT>" & vbCrLf
    Page.RegisterClientScriptBlock("key_setFocus", strScript)
    End Sub
  86. WOLF 1/10/2006 11:33 AM
    Gravatar
    oops srry...

    that was VB and must have been c #
  87. Joel Karafin 1/10/2006 2:17 PM
    Gravatar
    Another satisfied customer. By the way, is this the best way to scroll the page somewhere to the middle, or to the bottom?
  88. Jim Zak 1/14/2006 3:57 PM
    Gravatar
    I can't seem to figure out what code to put where. I'm using Visual Studio .NET 2003. with C#.

    Where to I put the "public static void SetFocus(Control control)" code?
    I tried putting it in my HTML code page between <script runat="server">
    and </script> tags and then place PageUtility.SetFocus(Auto_Amt); in the cs code behind page in the Page_Load method.

    PageUtility is not recognized when I compile.

    I'm using C# Code Behind and set to use Javascript on the Client Side.
    I'm using public class WebForm1 : System.Web.UI.Page for my webform
    Not sure if I have given enough information.

    I was able to get my columns to sum and post the sum in the sum field after PostBack but I'm not able to set focus to the correct field. If I'm in Field 1 and press tab and the AutoPostBack gets fired I want it to calc and then go to column 2, then when I enter input into column 2 and tab I want it to AutoPostBack and calc and set focus to column 3 etc....

    I'm getting the AutoPostBack to work, the calc to recalc etc but the focus is lost.

    I see all the good examples but I'm a bit new to .NET and looking for someone that could guide me in the right direction. My background is in Windows Programming with PowerBuilder.

    Thanks in Advance :)
  89. Sarah 1/17/2006 6:44 AM
    Gravatar
    Ryan,

    Excellent post - very helpful! Do you have an update for Visual Studio 2005?

    Thanks!
  90. friendster 1/18/2006 3:10 AM
    Gravatar
    if anyone know how to change the tabindex of asp.net control while pressing enterkey with a button present in the webform. please mail me

    rajeevgopi@sify.com
  91. Ryan Farley 1/18/2006 8:29 AM
    Gravatar
    Jim Zak,

    PageUtility is the name of the class where I put the function. You don't have to put it in a separate class if you don't want, you could just put it in the same class/webform/etc that you're calling it from (in which case of course you need to drop the class name and just call the function directly).

    Sarah,

    In .NET 2.0 the Page class has a built in SetFocus method, so no need to implement one yourself.

    -Ryan
  92. Sriram 2/2/2006 6:06 AM
    Gravatar

    i've been searching for this for more than two days. atlast the code that worked is urs. with out any modifications


    good work

    thanks

    Sriram
  93. Ben 2/6/2006 3:07 PM
    Gravatar
    Thanks Ryan. I can keep avoiding all javascript tasks thanks to people like you.
  94. Mich 2/6/2006 8:24 PM
    Gravatar
    Thanks for this wonderful work-around! Really helpful! Great Job!
  95. Dom 2/13/2006 1:24 AM
    Gravatar
    Cheers, mate!
  96. Yury 2/13/2006 6:24 AM
    Gravatar
    Great code, works for me. Thanks, man!
  97. RP 2/15/2006 5:23 AM
    Gravatar
    Good Work.
  98. Mike 2/22/2006 6:07 AM
    Gravatar
    Awesome! Thanks to Justin for the VB conversion too.


  99. Don 2/24/2006 8:46 AM
    Gravatar
    I have try using the code in VB.NET but it doesn't work for me.

    Is this the correct way of calling the class to get it to work or there more to it?

    Dim ControlFocus as PageUtility
    ControlFocus.SetFocus(txtName)
  100. Ryan Farley 2/24/2006 9:10 AM
    Gravatar
    Don,

    It depends on where you put it. If you have it as a non-static/shared method in a class named ControlFocus, then yes, you are doing it right.

    There's no need to put in a class if you don't want to. If you just pasted it into the code for the page itself, then you could just call it as:

    SetFocus(txtName)

    Make sense?

    -Ryan
  101. Don