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 2/24/2006 10:00 AM
    Gravatar
    Well, I created the class name, "PageUtility". Afterwards, I just copy your code(The VB version that someone converted). Then created a variable for it like the previous post. If that is correct then I still can't get it to work..
  102. Don 2/26/2006 3:22 PM
    Gravatar
    This is the error I recieve, which is related to my txtName object.
    Object reference not set to an instance of an object.

    Here is my code in the PageUtility class:
    Public Class PageUtility
    Sub SetFocus(ByVal ctrl As Control)
    Dim sb As New System.Text.StringBuilder("")
    With sb
    .Append("<script language='JavaScript' type='text/javascript'>")
    .Append("function SetFocus()")
    .Append("{")
    .Append("document.")

    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)
    .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
    End Class


    Do y'all see anything wrong that is causing the problem?
  103. Christopher Simmons 2/28/2006 3:01 PM
    Gravatar
    Ok all this code is for .net 1.1 but no .net 2 the classes have changed for calling the registerclientscriptblock as well you need a type now, but regardless it's kinda the same, actually what you guys are trying to do in .net the framework allready has a class for this page.setfocus(yourControl)
    The only problem is both the frameworks implementation and the implementation on this page won't work if you have your stuff in a user control, unless i'm missing something? i'd love to know?

    How do you get the page.setfocus(mycontrol) to work when in a user control?

    Oh and if anyone can help write a couple of questions at www.aspnetsource.com
  104. ZLA 3/3/2006 9:02 AM
    Gravatar
    The problem with a user control is that it is not a native html field - you need the field inside of the user control.

    What I've done is add a SetFocus method to my usercontrol so that instead of calling page.setfocus(myUserControl), I call myUserControl.SetFocus(). This SetFocus control then calls page.setfocus(myActualControl).

    For example if I have a user control with three textboxes (Textbox1, 2 and 3), the usercontrol SetFocus method could execute page.setfocus(TextBox2). On the page, I would just call MyUserControl.SetFocus()
  105. PY 3/4/2006 1:26 AM
    Gravatar
    in .net web project i am having one grid with buttoncolumn Select.

    on click on select in grid. i have written code in this routine

    Private Sub DtgAddress_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DtgAddress.SelectedIndexChanged

    DALConn.SetFocus(btnSubmitAdd, "form1")
    end sub

    btnSubmitAdd is a web control on that page...


    but its not working....
  106. Raskawa 3/10/2006 7:39 AM
    Gravatar
    Great fix - thanks!
  107. Sripathi R Rao 3/14/2006 2:57 AM
    Gravatar
    I created one text box in a form, and typed some thing in it, and then i click save. when i again visit same form to edit some thing, the focus is given to the starting position not at the end of the data. so please suggest me.
  108. Ryan Farley 3/14/2006 1:20 PM
    Gravatar
    Sripathi,

    In order to be able to leave the page, you'll need to persist the control you want focused in the session so you can set it again when the user returns to the page.

    -Ryan
  109. KS 3/14/2006 5:06 PM
    Gravatar
    The C# code works for me, but with one major flaw -- the focused control (a DropDownList) gets focus, but is scrolled to the bottom of the screen, which is the exact opposite of what I want.

    An earlier poster, paladin something or other, had the same problem.

    Is anyone else experiencing this issue?

    More importantly, does anyone know how to fix it?

    Thanx!
  110. Aaron 3/29/2006 5:02 AM
    Gravatar
    Hey all,

    Let me start by repeating some other people; this function is great! You have saved me a lot of time and effort and have greatly increased the worth of my page.

    With that said, I would like to comment on some of the 'problems' other posters have been having because I ran into them but was able to get them solved.

    First, the code worked for me on a test page that I made but wasn't working on my 'real' page where i needed it. Turns out that there was another function that was also using the javascript onload= property. Thus, the setfocus onload= was not being recognized. I found this 2nd onload= by viewing the source code of the rendered html page, not my source code in dev mode, because the onload= was in a separate footer page in my project and was therefore not even on the code page that I was looking at.

    Second, once working properly, the setfocus function will work with asp:textbox controls, not just html textarea controls. Also, it will work for textbox controls inside a panel, a div, a table, etc...

    Third, I loved the function but was also annoyed like everyone else at the fact that the focused control would always be at the bottom of the page.
    I found some scrolling script, and adding 1 line of new code to the setfocus function solves the problem - immediately after the line
    .Append(".focus();")
    you can add:
    .Append("window.scrollBy(0,150);") ' // horizontal and vertical scroll increments

    That's it, problem solved. I actually went one step further and added an optional ScrollAmount parameter to my SetFocus function and placed that where the 150 is, this way you can set the scroll amount as you like on the fly. Setting it to an out of bounds number, like 2000, does not cause and error, simply scrolls to the bottom of the page.

    Anyway, hope that helps everyone, you guys have all certainly helped me!

    Thanks again, enjoy the scroll, cya :)
  111. Baba 4/6/2006 1:23 AM
    Gravatar
    Hello,
    May be this is another way to do it!

    Public Sub setFocus(ByVal ctrl As System.Web.UI.Control)
    Dim strS As String
    strS = "<SCRIPT language='javascript'>document.getElementById('" & ctrl.ID & "').focus() </SCRIPT>"
    Page.RegisterStartupScript("focus", strS)
    End Sub

    Call it like that:
    setFocus(abcdtextbaox)

    Baba
  112. CodeDoctor 4/6/2006 9:06 AM
    Gravatar
    SMARTNAVIGATION and Setting Focus (FIXED)

    I, like the rest of you, have the need to have SmartNav on. However, setting focus will not work regardless of what attempts are made.

    Upon researching this for several hours, I have discovered a way to implement this functionality.

    SOLUTION:

    I have the solution to get SmartNav to work with setting focus, this will require a little backend work.

    First, create a new VB Class
    PageHelper.vb

    Public Class PageHelper
    Inherits System.Web.UI.Page
    Protected WithEvents PageBody As _ System.Web.UI.HtmlControls.HtmlGenericControl

    Public Property NewSmartPageNavigation() As Boolean
    Get
    NewSmartPageNavigation = MyBase.Page.SmartNavigation
    End Get
    Set(ByVal Value As Boolean)
    MyBase.Page.SmartNavigation = Value
    End Set
    End Property
    Public ReadOnly Property oPageBody() As HtmlGenericControl
    Get
    oPageBody = PageBody
    End Get
    End Property
    End Class

    This class becomes the top level Page class that all of your code behind files must implement.

    In the Code behind of the MAIN page, change the following line

    Inherits System.Web.UI.Page
    to:
    Inherits <yourproject>.PageHelper

    Now the page will be inherited from your new class, which inherits
    the page class.

    Once this is done, ensure you open up the HTML of the MAIN page you are using, and do the following to the Body Tag.
    #Note: This MAIN page can be the page housing many different Web User controls.

    <body runat=server id=PageBody>

    This makes it a server level control (HTMLGenericControl) to be specific, that is capable of being accessed in VB code.

    And finally, in each of your user controls, where you are clicking an action to go into edit mode, or navigating. Put the following code there.

    Dim PH As PageHelper
    PH = Me.Page
    PH.oPageBody.Attributes.Add("onload", "javascript:document.forms[0]['" & TextBox1.UniqueID & "'].focus();")

    This implementation allows for setting the BODY onload event, instead of the Window onload event. This way, smart nav can still operate, and allow for its implementation of saving screen position and focus data of a page during the window onload event.

    This has been fully tested with multiple pages housing over 14 different custom Web User Controls. All written in good ole VB.NET.

    I hope that this saves you a ton of time, it would have saved be a ton.

    CodeDoctor








  113. boy named jib 4/14/2006 9:10 AM
    Gravatar
    I use a static public method (C#) that registers a startup script, passing in the Object Id and the Page object simply setting focus. This way any page can call it.

    static public void FocusThisObject(string sId, Page Page, string sBGColor)
    {
    Page.RegisterStartupScript("focus_focus",
    "<script>var o=document.forms[0]."+sId+";"+
    "o.focus();"+(sBGColor==""?"":"o.style.backgroundColor='"+
    sBGColor+"'")+";</script>");
    }
  114. Ryan Farley 4/14/2006 10:18 AM
    Gravatar
    boy named jib,

    That's basically what the code in the post does as well, except it figures that stuff out on it's own without the need for you to pass it in ;-)

    -Ryan
  115. Mike 4/19/2006 5:34 AM
    Gravatar
    To fix the newline in constant error, split the </SCRIPT> tag in two or more strings such as "<" + "/SCRIPT>". For the C# example that changes it to:

    sb.Append("<" + "/script>");


    Thank you much for the initial post. Was very helpful.
  116. gszhang 4/22/2006 9:46 PM
    Gravatar
    if TextBox1 in a Table1 and Table1 is hidden, When I click a button to make the Table1 Visible How can I set the focus to TextBox1? Thanks.
  117. gszhang 4/23/2006 5:56 AM
    Gravatar
    When Table1 is not hidden SetFocus(TextBox1) works well,but When Table1 is hidden where is the trigger to SetFocus(TextBox1)?
  118. Sandy 5/3/2006 3:00 AM
    Gravatar
    Hi Ryan,
    I have a textbox in the footer row of a datagrid and the datagrid is having a div tag with the Auto overflow property ......i have used the set focus code and it worked fine......but when i reduced the height of the div tag a little bit, it's setting the cursor in that textbox in the footer row but that footer row is not being visible during the page load event....but if i scroll my mouse down i'm able to see that the cursor is there in the textbox.....please help....
  119. Sandy 5/3/2006 3:08 AM
    Gravatar
    I have a textbox in the footer row of a datagrid and the datagrid is having a div tag with the Auto overflow property ......i have used the set focus code and it worked fine......but when i reduced the height of the div tag a little bit, it's setting the cursor in that textbox in the footer row but that footer row is not being visible during the page load event....but if i scroll my mouse down i'm able to see that the cursor is there in the textbox....

    can anybody help me????

    Thanx in advance....
  120. Kieran 5/18/2006 3:20 AM
    Gravatar

    Hi,

    Firstly this works great. However, for me, i need to keep the cursor to the end of the last character the user has entered in the textbox (my form submits 'onkeyup').

    I see that Ryan suggested for a similar question asked earlier -
    "In order to be able to leave the page, you'll need to persist the control you want focused in the session so you can set it again when the user returns to the page."

    I am unsure how to keep the this is a session and therein keep the cursor at the end of the last character entered as the user types...could anyone clarify this for me.

    Thanks.


  121. Giz 5/30/2006 9:13 AM
    Gravatar
    Hi, I tried to implement the code in my page, but it doesn't work, although the page doesn't send an error, the focus is lost when the page is post back. I'm trying to set the focus in a text box that is into a datagrid, and the datagrid is into a panel. Thanks
  122. Ryan Farley 5/30/2006 9:25 AM
    Gravatar
    Giz,

    Things are different for controls inside a datagrid. Try looking at the source of the page and see the name of the text control along with the heirarchy of elements to get there (using the Developer toolbar for IE or Firefox makes this an easy task).

    Once you have all of that figured out it is easy enough to modify the code that emits the javascript to use the scheme of the textbox in the grid. Know what I mean?

    Good luck.

    -Ryan
  123. Mark Prasanna 6/6/2006 9:49 PM
    Gravatar
    It's working fine. Thank
  124. MZD 6/9/2006 12:02 PM
    Gravatar
    To Sandy,

    //Scrolling the DIV to the bottom
    //hdnDivPositionID -- hidden field ID
    // hidden field will have some large value of 999999
    //divID is the id for the DIV tag

    function keepScrollPosition( hdnDivPositionID,divID)
    {
    var divObj = document.getElementById(divID);
    var hdnDivPosition = document.getElementById(hdnDivPositionID);
    if(!(divObj==null || hdnDivPosition==null))
    divObj.scrollTop = hdnDivPosition.value;
    }

    the idea is to assign divObj.scrollTop = some value larger than the div size.
  125. Randy Blackburn 6/10/2006 8:45 AM
    Gravatar
    Regarding the datagrid sample code: Implementation for asp:datagrid edited item column - by Wole Ogunremi

    1. Where is this code placed? I am getting an error regarding the e. ("not accessible in this context because it is private") in my vb translation...

    2. I'm interested in the cell SELECT functionality. How would that be implemented in the non-grid-oriented code provided by others in this thread?

    3. Does anyone have a vb version that allows any kind of control (grid/cell, asp, html, webUserControl) to be fed in?

  126. Randy Blackburn 6/10/2006 5:39 PM
    Gravatar
    1a. The only place that this worked for me was in the itemdatabound module of the grid. How would I change things to call the routine generically in a PageUtility class?

    2a. This DID select the text in the proper cell. However, if I try to tab to the next column, it took me to a field on the ie.browser... is there a way to fix/change that?

    Thanks again.
  127. Bharath 6/16/2006 1:38 PM
    Gravatar
    Good job. Very useful. Thanks a lot
  128. Dan A. 6/21/2006 10:02 AM
    Gravatar
    Great bit of code.
    For us really lazy folks, you should inlcude the namespaces used as well.
  129. Naveed 6/28/2006 9:28 AM
    Gravatar
    Thank you very very much!
    This saved me a great deal of time!

    -Naveed
  130. Nasrulllah 6/29/2006 9:07 PM
    Gravatar
    I had some problems with the drop down list control on postback page load event is called but i want to stil focus on that control.
  131. Cash 7/11/2006 4:17 AM
    Gravatar
    im not able to get focus on the data grid when im clicking in the page number ie;pagenumber change event ....the focus is staring frm top of the form
  132. Giammin 7/12/2006 5:24 AM
  133. Prasanth Joseph 7/21/2006 11:53 PM
    Gravatar
    Hello Ryan Farley,

    Thank you very much for your valuable effort.It helped me a lot, in my coding and save my time.Once again wish you a bright future

    By Prasanth Joseph
  134. Kevork Yerevanian 7/24/2006 8:37 AM
    Gravatar
    Thanks Ryan,

    Beautiful... Just copied and pasted the code and it works beautifully. Thanks for sharing!!!

    Kevork Yerevanian
  135. Amarjit Singh 8/8/2006 6:58 PM
    Gravatar
    This method seems great but since it works for only html controls i.e. HTML Text Field Control, not ASP.NET Textbox Control; There is an easier way:-

    Page.RegisterStartupScript("SetFocus", _
    "<script>document.getElementById('" & HTML_INPUT_BOX.ClientID & _
    "').focus();</script>")

    Step 1: Insert html text field on to the form, right click on the control and select 'Run as a server control' option (just so you could use it for other reasons in the vb code behind). Give this control an ID (In the code above, the ID given to this control is 'HTML_INPUT_BOX').

    Step 2: Paste the given code under your page load in the vb file.

    Step 3: Change the 'HTML_INPUT_BOX' to the ID you gave to your control in thr form.

    Hope this helps. The code given above is for ASP.NET 1.1 and is not mine, i got it from http://www.eggheadcafe.com/forums/ForumPost.asp?ID=79729&INTID=6

    Hope it helps.

    Amarjit
  136. Ryan Farley 8/8/2006 7:41 PM
    Gravatar
    Amarjit,

    Uh, I don't follow. The code in the article above *is* for ASP.NET TextBox controls (did you read it?). It emits the same javascript you mention in your comment, but it does so in a generic way (so that it would work generaically for *any* textbox you pass to it. It was built this way so you could also at runtime programatically set focus to a control (like in a postback) and not hard code this for a certain control.

    -Ryan
  137. Simi 8/9/2006 2:39 PM
    Gravatar
    Hi Ryan,

    I am having a panel in which I give the data and save it.on the top of it is the parent panel where the save button is. after saving the data, the focus must return to the panel which I am giving the data, so that the user can see his saved data in the datalist without having to scroll down.How can I make use of ur code in my context as such I am trying to set the focus to the boundtextbox on the data panel of the sub panel.
  138. Anistel 8/20/2006 11:46 PM
    Gravatar
    It can't use with a user control. Any solution.
  139. waycool 8/25/2006 9:59 AM
    Gravatar
    I used the script to set focus to a textbox in a datagrid which works fine except the textbox does not response to any key press except "Delete" key. When the "Del" key is pressed it will start deleteing characters but I am not able to type in anything until I hit "tab" key which bring the focus to the next textBox. I have to use "shift+tab" to bring the focus back then I am able to type characters. Anyone know what why this is happending ?
  140. Bhavesh Patel 9/13/2006 4:28 AM
    Gravatar
    Hi,

    I have a web user control on my page. And i want to set focus of any control of that web user control. So how can i do that.

    Mail me solution on 78.bhavesh@gmail.com

    Thanks
    Bhavesh Patel
  141. NevStar 9/29/2006 3:56 AM
    Gravatar
    Superb! thanks for your efforts all.
  142. Ritesh 10/25/2006 2:11 PM
    Gravatar
    Hi Ryan,

    I have a textbox (ID=Textbox1) on top of the datagrid and have a calendar control inside the datagrid. When i click on calendar control, i call SetFocus function inside of ItemCommand function of datagrid. It does post back but doesn't set the focus on Textbox which i am having on top of datagrid. Please let me know if i am doing any mistake calling the setfocus function.

    Any help would be greatly appreciated.

    Thanks in advance,
    -Ritesh

  143. djcomlab 11/14/2006 9:39 AM
    Gravatar
    This works like a charm. Thanks for the VB translation.
  144. Ray 11/15/2006 4:53 PM
    Gravatar
    the vb translation up the very top by Justin Blaske worked for me. Thanks heaps, saved me heaps of time.
  145. David 11/16/2006 11:39 AM
    Gravatar
    thx, work fine.

    i just add a if to verify that the control really exist!

    david

    here my VB.Net version
    ****************************************
    Public Shared Sub SetFocus(ByVal voControl As System.Web.UI.Control)

    Dim oSb As System.Text.StringBuilder
    Dim p As System.Web.UI.Control

    Try
    oSb = New System.Text.StringBuilder

    oSb.Append(vbNewLine)
    oSb.Append("<script language='JavaScript'>")
    oSb.Append(vbNewLine)
    oSb.Append("<!--")
    oSb.Append(vbNewLine)
    oSb.Append("function SetFocus()")
    oSb.Append(vbNewLine)
    oSb.Append("{")
    oSb.Append(vbNewLine)
    oSb.Append(vbTab)
    oSb.Append("var oCtrl;")
    oSb.Append(vbNewLine)
    oSb.Append(vbNewLine)

    oSb.Append(vbTab)
    oSb.Append("oCtrl = document.")

    p = voControl.Parent

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

    oSb.Append(p.ClientID)
    oSb.Append("['")
    oSb.Append(voControl.UniqueID)
    oSb.Append("'];")
    oSb.Append(vbNewLine)
    oSb.Append(vbNewLine)

    oSb.Append(vbTab)
    oSb.Append("if (oCtrl != null)")
    oSb.Append(vbNewLine)
    oSb.Append(vbTab)
    oSb.Append("{")
    oSb.Append(vbNewLine)
    oSb.Append(vbTab)
    oSb.Append(vbTab)
    oSb.Append("oCtrl.focus();")
    oSb.Append(vbNewLine)
    oSb.Append(vbTab)
    oSb.Append("}")

    oSb.Append(vbNewLine)
    oSb.Append("}")
    oSb.Append(vbNewLine)
    oSb.Append("window.onload = SetFocus;")
    oSb.Append(vbNewLine)
    oSb.Append("// -->")
    oSb.Append(vbNewLine)
    oSb.Append("</script>")

    voControl.Page.RegisterClientScriptBlock("SetFocus", oSb.ToString())
    Catch ex As Exception
    Finally
    oSb = Nothing
    p = Nothing
    End Try

    End Sub
    ****************************************
  146. Vikas 11/21/2006 7:34 AM
    Gravatar
    Thank You so much.Works Amazingly :-) You are simply Awesome
  147. Hiren Patel 11/22/2006 9:40 AM
    Gravatar
    thanks so much...the code works great!
  148. Sam 11/24/2006 2:37 AM
    Gravatar
    Brilliant ! Thanks, works brilliantly.
  149. Micela 1/5/2007 7:13 AM
    Gravatar
    Hi,
    Thank you very much. It works......
    Thank you,Thank you,Thank you
  150. yusuf 1/17/2007 7:44 PM
    Gravatar
    Thank u
  151. yaser 1/31/2007 4:22 PM
    Gravatar
    tnx
  152. mrudula 3/7/2007 2:12 AM
    Gravatar
    i think its really good .but its not working for me .
    the problem i m facing is that when i try to write
    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
    then after ' page. ' its not giving me RegisterClientScriptBlock

    is it because of that i havn't enable scripting in my application if so then
    please suggest me the way 4 it
    or may b because of i havn't use some namespace 4 it
    plz help me out as early as possible
    thanks
  153. Dylan 3/20/2007 10:24 PM
    Gravatar
    Thanks man, that worked like an absolute charm. Elegant slice of code.
  154. shantanu agarwal 3/25/2007 11:23 PM
    Gravatar
    Hi,
    I need to pu focus on the current control after the page is posted or reloaded again. mean if control in on textbox 3 and i clicked the button and posted the page then when page gets reloaded then control should be on textbo3 again.
    you can mail me solution on sagarwal80@yahoo.com.

    Shantanu
  155. Vishi 4/2/2007 2:00 PM
    Gravatar
    Has someone been able to run something like this on mobile ASP? The register ClientScriptBlock won't work in mobile ASP.
  156. Diana 4/3/2007 10:30 PM
    Gravatar
    in a user control i have to set focus to a textbox. registerclientscriptblock and rgisterstartupscript is not working here. plz help me out as early as possible
    thanks
  157. Roshan Srivastava 4/5/2007 6:43 AM
    Gravatar
    Really very good code.
    Thanks
  158. Fausttt 4/6/2007 10:56 AM
    Gravatar
    thanks for the code. it works for setting focus. Does anyone know how to set the cursor position in a textbox? so set the focus on a textbox AND make sure the cursor is at the END of the text already in the box?
  159. Lisber 4/8/2007 8:05 AM
    Gravatar
    Excelent job, the ASP .NET 2.0 team sure read this and implement it at the core.

    i don't read all the posts so maybe this was said before, in order to use the focus in asp 2.0 you just simple need to call the Focus Method at code behind. For example

    TextBox1.Focus();

    That's it, for this things is that i love asp and hate PHP, here we have support and server controls to do the dirty work :P

    Cheers
  160. Pete 5/5/2007 12:14 PM
    Gravatar
    hahahahahahahahahahahahahahaha

    After all these posts...that last post is all you have to do!!!! How hard is that? haha Thank you Lisber.
  161. Ryan Farley 5/5/2007 3:37 PM
    Gravatar
    Pete,

    If you notice the date of the original post, Dec 2004, you'll understand that this was written before ASP.NET 2.0 was out. As well, many companies still develop in ASP.NET 1.1. The method described from Lisber, which has been mentioned many times on this post, is only available in ASP.NET 2.0. That is, of course, the way to go if you're developing in 2.0. If not then the original post is you're only method to accomplish this.

    Thanks.

    -Ryan
  162. Ryan Farley 5/5/2007 3:38 PM
    Gravatar
    Pete,

    If you notice the date of the original post, Dec 2004, you'll understand that this was written before ASP.NET 2.0 was out. As well, many companies still develop in ASP.NET 1.1. The method described from Lisber, which has been mentioned many times on this post, is only available in ASP.NET 2.0. That is, of course, the way to go if you're developing in 2.0. If not then the original post is you're only method to accomplish this.

    Just because you're late to the game, don't knock the teams that have been sweating it out on the court. hehe.

    Thanks.

    -Ryan
  163. Jocke 5/9/2007 6:11 AM
    Gravatar
    Hi, did anyone solve the problem that when setting focus on a textbox it's always sets focus before the first character in the textbox?
  164. Lawrence 5/22/2007 7:11 AM
    Gravatar
    Hi all,
    I've just joined the long conversations.
    Can someone please help me with following:

    I have an asp TextBox (not a HTML clientside) and I'm simply using
    the this.SetFocus(TextBox1). Until now this solution worked great.
    BUT now this control have to go in a panel and there all hell brakes loose:
    For 0,5 sec you can see the cursor in the textbox (does not happen when I comment the method!) but than it looses focus (wich is NOT what I want).

    I'm using VS 2005 PRO in C#, MSSQL2005 and AJAX

    Can someone please help me, it's very frustrating.

    thx!
  165. Anonymous 5/25/2007 9:54 AM
    Gravatar
    Compiler Error Message: CS0246: The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)

    Source Error:



    Line 742: public static void SetFocus(Control control)
    Line 743: {
    Line 744: StringBuilder sb = new StringBuilder();
    Line 745:
    Line 746: sb.Append("\r\n<script language='JavaScript'>\r\n");

  166. Ryan Farley 5/25/2007 10:11 AM
    Gravatar
    Anonymous,

    To use the StringBuilder class you must add a using directive for "System.Text".

    -Ryan
  167. gevyvojr 6/18/2007 10:10 PM
    Gravatar
    fsphvwep http://ojrbynbt.com tydvscoz avjgytve [URL=http://intmmfya.com]ymuaqrnp[/URL] <a href="http://uzvhtsul.com">vsohhgyd</a>
  168. oxeuiksv 6/20/2007 2:14 AM
    Gravatar
    anuzqrhr http://ihkurazn.com jyiybhkh yddpmriy
  169. Adirondak 6/21/2007 8:10 AM
    Gravatar
    Thanks for the elegant solution. I would be interested in seing your PageUtility class. Anything else interesting in it?

    Anyway, thanks, this works great.
  170. suresh verma 6/23/2007 6:52 PM
    Gravatar
    nice script and easy to use
  171. Brian 6/28/2007 12:28 PM
    Gravatar
    I have tried putting the SetFocus call inside a button click event. This does not write the javascript to the page. Then I tried putting the SetFocus call inside the pre-render method and this writes the javascript to the page, but does not set focus to the proper text box.

    It is frustrating because I have this set focus routine working on a brand new project, it is just that it doesn't work on this existing one.
  172. Bismarkcount 6/29/2007 8:14 AM
    Gravatar
    Thnx for the scripts. works perfectly!! :0)
  173. roni 7/16/2007 10:54 PM
    Gravatar
    just use Page.RegisterStartupScript.
    It emits a client-side script block in the page response

    Page.RegisterStartupScript("SetFocus", "<script>document.getElementById('" & Ctrl.ClientID & "').focus();</script>")

  174. wugsmbsw 8/1/2007 4:24 AM
    Gravatar
    <a href="http://oeefstvb.com">jluojdnd</a> [URL=http://htygiirg.com]gnefhyid[/URL] gcktdlnf http://pipkazen.com pqbviazs nyyeoquk
  175. Ricardo Mendes 8/7/2007 1:18 PM
    Gravatar
    using AJAX you just need to use this command:

    ScriptManager1.SetFocus(TextBox1)

    Ricardo
  176. Chaitanya 8/27/2007 10:12 PM
    Gravatar
    gr8 job.....it's working fi9....
    thanks for the code..
  177. Ravinder 10/4/2007 5:13 PM
    Gravatar
    Hi all,

    Given codes are good to see, I felt happy to use them, but no sample coding is working in my mobile application in .net

    Please give me a good sample one on setfocus to a textbox/button, and keyboard event/function keys for my symbol mc9090 mobile application.

    If I use above codes I'm getting "A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property." error

    Please guide...me...

    Thanks...
    Ravin
  178. Ravinder 10/4/2007 8:05 PM
    Gravatar
    Hi all,

    I got the setFocus..............., its running good....


    Thanks
    Ravin
  179. smithers 10/19/2007 5:35 AM
    Gravatar
    Ryan,

    First of all, thanks for your great work.

    In the beginning of this post Joel talked about the server control and you talked about using base page class. Did you write those, or at least your idea (base page class)? I am a newbie and want to know how to do it. Where can I them?

    Thank you,
    Smithers
  180. Rick Metz 10/26/2007 7:04 AM
    Gravatar
    Sweet !!!!!!!!!

    Thanks.

    ~ Rick
  181. rellymr 10/29/2007 2:25 AM
    Gravatar
    This was very handy and worked exactly as I wanted. Thanks very much!
  182. Cool Job Ryan and Justin for the 10/29/2007 10:03 PM
    Gravatar
    GReat work both of Ya.. saves tons of work and effort
  183. Saurabh Tyagi 12/20/2007 11:02 AM
    Gravatar
    This function is already available with 2 overloads
    use
    Page.SetFocus(Control control)
    or
    Page.SetFocus(String ControlId)

    So why we need to write extra code while it's already there in
    Page class
  184. lakshmi 1/28/2008 3:26 AM
    Gravatar
    can i get a code to set focus after getting a message box
  185. Sukhminder Singh 2/18/2008 10:00 PM
    Gravatar
    Hi all!

    I have a text box (which is hidden initially) and a link button in a user control. I set the text box to visible on the click of this link button.
    But, the problem is It does set the focus to the text box, when I set text box's visible property to true.

    The code is given below

    Page.RegisterStartupScript("SetInitialFocus", "<script>document.getElementById('" + txtLinkName1.ClientID + "').focus();</script>");
  186. theAsocialApe 4/3/2008 7:42 AM
    Gravatar
    thanks -
    didn't use your whole solution, but i found what i needed here (control.UniqueID) that let me get to the control within the control
  187. Web Designer 4/28/2008 12:13 PM
    Gravatar
    I want to click on the search text box and it should make the search button the default button and it should disable the login field validation too, so that the page can be posted back without filling in the username and password. Can anyone help?
  188. ram majji 6/1/2008 6:35 PM
    Gravatar
    The solution works fine on development environment but when deployed into windows 2003 IIS server. Please find the below code place in page_load and it resolves the issue (I am also using ModalPopUpExtender as well)

    if (!this.ClientScript.IsStartupScriptRegistered("Startup"))
    {
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type=\"text/javascript\">");
    sb.Append("Sys.Application.add_load(modalSetup);");
    sb.Append("function modalSetup() {");
    sb.Append(String.Format("var modalPopup = $find('{0}');", this.programmaticModalPopup.BehaviorID));
    sb.Append("modalPopup.add_shown(SetFocusOnControl); }");
    sb.Append("function SetFocusOnControl() {");
    sb.Append(String.Format("var textBox1 = $get('{0}');", this.ZipCode.ClientID));
    sb.Append("textBox1.focus();}");
    sb.Append("</script>");
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sb.ToString());
    }
  189. LA 6/19/2008 10:58 AM
    Gravatar
    Hi All,

    I need one help from you. I am trying to set focus todifferent controls after my different PostBack events, butthis.ScriptManager1.SetFocus(myControlName.ClientID); is not working.

    In my ASPX page I have RAD CONTROLS (RadComboBox and RadCalendar) and alsoI am using AjaxControlToolkit Controls (ToolkitScriptManager andModalPopupExtender) also.

    In my page, RadComboBox is inUpdatePanel - ContentTemplate area and on its SelectedIndexChangedfunction I am trying to set focus to another Control using the abovecode:

    this.ScriptManager1.SetFocus(myControlName.ClientID);

    but this is not working... Do anyone know any solution for this?

    Thanks...
  190. Lesh Augustus 6/20/2008 6:13 AM
    Gravatar

    Hi All,

    I got solution for the above issue. I was trying to set focus using the code

    this.ScriptManager1.SetFocus(myControlName.ClientID);

    and I wrote this code in my SelectedIndexChanged Event Function. That time this code didn't work.

    Now I changed this code to Page Load Function i.e.

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    this.ScriptManager1.SetFocus(myControlName.ClientID);
    }
    else
    {
    this.ScriptManager1.SetFocus(GetPostBackControl(this.Page).ClientID);
    }
    }

    Here I am using a function GetPostBackControl() to identify the current postbacking control and I am setting focus to the same control. If you want to move focus to any other control, just use a Switch Statment.


    public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page)
    {
    Control control = null;
    string ctrlname = page.Request.Params["__EVENTTARGET"];
    if (ctrlname != null && ctrlname != String.Empty)
    {
    control = page.FindControl(ctrlname);
    }
    // if __EVENTTARGET is null, the control is a button type and we need to
    // iterate over the form collection to find it
    else
    {
    string ctrlStr = String.Empty;
    Control c = null;
    foreach (string ctl in page.Request.Form)
    {
    // handle ImageButton controls ...
    if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
    {
    ctrlStr = ctl.Substring(0, ctl.Length - 2);
    c = page.FindControl(ctrlStr);
    }
    else
    {
    c = page.FindControl(ctl);
    }
    if (c is System.Web.UI.WebControls.Button ||
    c is System.Web.UI.WebControls.ImageButton)
    {
    control = c;
    break;
    }
    }
    }
    return control;
    }

    Thank you,
  191. Nitin Reddy Katkam 6/29/2008 9:38 PM
    Gravatar
    @Lesh

    Hi!

    Although I never had to set the focus manually to the postback control, I find the following statement to be a nice tip for me to note down:
    this.ScriptManager1.SetFocus(GetPostBackControl(this.Page).ClientID);

    Cheers,
    Nitin
  192. ASP Net 2.0 Migration 9/4/2008 12:13 AM
    Gravatar
    Nice code example... Great post Ryan...
  193. ramneek maan singh 9/9/2008 1:41 AM
    Gravatar
    Exactly what i was looking for!!!
    Thanks very much.
  194. Manmadha Rao M 9/16/2008 7:44 AM
    Gravatar
    Dear Mr. Ryan,

    I have designed a Calculator in ASP.Net with VB.Net server code. The
    code for 'setFocus' method is working fine for the web controls I used in the programme, but when I used this 'setFocus' method in MOBILE WEB CONTROLS, this code is not working; instead I am getting an error
    message. Can you help me to solve the problem

    Manmadha Rao
















  195. Sanjay Kr. Chaki [India] 10/27/2008 1:17 AM
    Gravatar
    Bravo! Its a great solution........
  196. Faisal 10/29/2008 8:00 AM
    Gravatar
    It worked perfectly for me!!
    Thanxx!
  197. Ryan Shaw 11/5/2008 3:39 PM
    Gravatar
    ASP.NET / C# 3.5

    in the code behind I used
    Control.Focus();

    IE: For a Login Control nested inside a LoginView:

    LoginView1.FindControl("Login1").FindControl("UserName").Focus();

    or if its not burried inside containers, just use .Focus(); or as previously mentioned Page.SetFocus(Control);

    many options...
  198. Devanand 11/5/2008 11:01 PM
    Gravatar
    Hey all

    I have diffrent problem as i have three asp buttons on the page and i want to set focus on the 3rd one each time. I already tried SetFocus fuction of Page and defaultfocus propery of control. JS focus method is also not getting effected as focus shifted to first button on the page (This is obvious). Can anyone tell me how to set focus on 3rd button after postback.

  199. Devanand 11/5/2008 11:05 PM
    Gravatar
    Hey
    I have diffrent problem as i have three asp buttons on the page and i want to set focus on the 3rd one after postback. I already tried SetFocus fuction of Page and defaultfocus propery of control. JS focus method is also not getting effected as focus shifted to first button on the page (This is obvious). Can anyone tell me how to set focus on 3rd button after postback.
  200. Asha 11/6/2008 9:20 PM
    Gravatar
    Hi All,

    Whether focus() method works in mozilla firefox browser

    Plz reply me
  201. Asha 11/6/2008 9:28 PM
    Gravatar
    Hi All,

    If Label.innerText property doesnot work in mozill browser plz write the code as fallows:


    document.getElementById("Label1").innerText="dsf";
    document.getElementById("Label1").textContent="dsf";

    this code helps because some of the browsers supports innerText and some browsers supports textContent property.
  202. Peter 11/13/2008 6:24 PM
    Gravatar
    With jQuery its EASY!!!

    Just add this in your aspx page at bottom
    before </asp:content>

    <script type="text/javascript">
    function pageLoad() {
    $(":text:first").focus()
    }
    </script>

    jQuery IS COOOL
  203. namdeo 11/20/2008 7:06 AM
    Gravatar
    any one help me

    i m using dropdown list box in my web page when page bind with data

    if i click on the same item which disply in dropdown control then the focus will go to another focus plz help
  204. geo 11/21/2008 9:36 PM
    Gravatar
    longest conversaion i ever had seen
  205. sagar 1/13/2009 9:05 AM
    Gravatar
    Javascript not working for update panel with synchronized triggers
  206. 1/20/2009 12:41 PM
    Gravatar
    SetFocus de un control | hilpers
  207. 1/22/2009 12:27 AM
    Gravatar
    Can we set focus in UserName of a LoginView | keyongtech
  208. ak 2/5/2009 12:59 PM
    Gravatar
    Update panel problem might be fixed by setting focus to another control before setting focus to the control you wanted focus
  209. sowmya 2/23/2009 1:41 AM
    Gravatar
    pls send me sample c=sharp coding for setfocus in textbox control
  210. JesseCuster 2/26/2009 6:48 AM
    Gravatar
    This is the code I used and it seems to work well in aspx and ascx files:

    public static void SetFocus(Control control)
    {
    Control p = control.Parent;
    while (!(p is System.Web.UI.Page)) p = p.Parent;

    ScriptManager sm = ScriptManager.GetCurrent((System.Web.UI.Page)p);
    sm.SetFocus(control);
    }

    And, then, in the code concerned (note I happened to put the above function into my Global class):

    Global.SetFocus(controlNameHere);
  211. Ahmad Nawazul (Thapa) 3/23/2009 6:57 AM
    Gravatar
    Thanks alot for this solution.
  212. Atif Rana 4/7/2009 6:17 AM
    Gravatar
    I would like to set focus to a textbox within datagrid on usercontrol. datagrid is within a callback control. this usercontrol is on a master page.

    I have tried most of suggestion suggested.
    Thanks in advance.
  213. Robert 4/12/2009 11:42 AM
    Gravatar
    "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:"

    Oh, yes you do! If you are using .NET 1.1 !!
  214. Ryan Farley 4/14/2009 11:47 PM
    Gravatar
    Robert,

    You've missed the point of the article. When this was written (in December of 2004), .NET 1.1 *was* the current framework version. This article outlines a way to set focus by emitting javascript onto the page from a .NET class.

    In .NET 2.0 there was a built in SetFocus method added to the Page class. This article gives you the equivalent functionality in .NET 1.1 (before the build in method existed).

    -Ryan
  215. GiulioRoma80 4/17/2009 9:12 AM
    Gravatar
    Così è troppo difficile???

    textBox1.Focus()
  216. Ryan Farley 4/17/2009 9:21 AM
    Gravatar
    @GiulioRoma80,

    If you notice the date of this post (December 2004), this was before .NET 2.0 came out. In .NET 2.0 the built in "Focus" and "SetFocus" methods were introduced. THis post outlines how to have the same functionality in pre-.NET 2.0

    -Ryan
  217. C#ristian 7/24/2009 2:25 PM
    Gravatar
    The question is: How can I implement that code in a mobile web form (aspx)?

    This link shows a solution: http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx

    but doesn't work at mobile aspx, only standard asp.net form.
    Actually, I'm testing my mobile web application at any PocketPC, with Windows Mobile 4.2 and 5.0.

    For example:

    protected void Page_Load(object sender, EventArgs e)
    {
    SetFocus(TextBox1);
    }

    This code works in standard asp.net web form, but throws an exception (System.NullReferenceException) in a mobile webform, so, I modify this code at:

    while (!(p is System.Web.UI.MobileControls.TextBox)) p = p.Parent;

    The exception disapears, but the focus doesn't work.
    Please, I need an answer :'(
    My email is freezer27@gmail. com
  218. 9/16/2009 9:25 AM
    Gravatar
    ??????????ASP.NET 2 ?????? ??????
  219. None 10/1/2009 6:07 AM
    Gravatar
    Para que te vas a matar haciendo todo ese código si tenés el metodo .Focus(); ???
  220. Ryan Farley 10/1/2009 7:39 AM
    Gravatar
    @None: Para que me voy a matar haciencdo todo ese codigo? Si puedes ver la fecha del articulo sabras que yo escribi este en Diciembre 2004 - antes de que saliera .NET 2.0. En .NET 1.1 el metodod ".Focus()" no existia asi que codigo como ese era necesario para poner focus en un control.

    -Ryan
  221. Marco 10/5/2009 12:04 AM
    Gravatar
    Thanks Ryan, worked a treat after translating it to VB.

    I did not implement this as a shared method in a separate class yet, but simply as a sub in an aspx page. Should this work to the owner's satisfaction, I think I'll implement it in our basepage class.

    Thanks again!

    --Marco
  222. vishnuvardhan 10/6/2009 4:07 AM
    Gravatar
    when the asp.net page reloading the page is going up..

    any one give the solution..
    thanks in advance
  223. software developer 10/26/2009 9:23 AM
    Gravatar
    Nice post,

    The code is great for me,

    Keep up the good work,

    Thanks
  224. TJ 11/5/2009 6:48 AM
    Gravatar
    Great simple solution! Thanks
  225. UNKNOWN 12/12/2009 1:30 AM
    Gravatar
    THANKS,gREAT
  226. rkapiljith 12/13/2009 1:33 PM
    Gravatar

    Somebody should definitely look above post for setting the focus at the last entered character...here is the code for the same!!!


    http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
  227. rkapiljith 12/13/2009 1:36 PM
    Gravatar
    Somebody should definitely look above post for setting the focus at the last entered character...here is the code for the same!!!


    http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
  228. Anuradha 2/21/2010 5:03 AM
    Gravatar
    To set focus in Login control's User Name text box,the following code works finely in c#...

    protected void Page_Load(object sender, EventArgs e)
    {

    TextBox tb = new TextBox();
    tb=(TextBox)Login1.FindControl("UserName");
    SetFocus(tb);
    }

  229. Akki 3/11/2010 1:27 AM
    Gravatar
    You are really great! Thanks for help!
    I can learn lot from u!
  230. Akki 3/11/2010 1:42 AM
    Gravatar
    Code works fine, but for setting focus back to control which was active before post-back, i have to check IsPostBack on page load,
    Because when u send "page" as parameter to "setfocus" function without checking "IsPostBack" it gives u error "NullReferenceException" during first page load!



    Also if u want to run this code on asp.net1.1 then u have to make following changes!

    if(IsPostBack)
    {
    Control c = GetPostBackControl(this.Page);
    SetFocus(c);
    }
  231. Akki 3/12/2010 2:47 AM
    Gravatar
    hi Ryan, function setfocus is working well for all other controls except Activex controls. will u please tell me reason for this and also suggest some remedy!
  232. Khan 4/24/2010 1:33 AM
    Gravatar
    Have you tried using this to set focus to a textbox in a AJAXpanel?
    I have an AJAX panel (asp:UpdatePanel) I put the setfocus method in another class.
    The page is like:
    I have two panels within an UpdatePanel; Each panel goes visible or invisible on a button click (also within the UpdatePanel)
    I just want to set focus on the textbox in the respective panel.

    I didn't work for me :(

    plz help
  233. macaroon 8/6/2010 2:11 AM
    Gravatar
    Really your blog have nice post so I became the permanent visitor of your blog.
    Thanks for sharing this useful information.
  234. 8/7/2013 9:04 AM
    Gravatar
    How to focus first field and select its content | Q Sites
  235. 7/5/2014 8:13 PM
    Gravatar
    [RESOLVED]Setfocusonerror is not working in firefox but working in IE | ASP Questions &amp;amp; Answers
Comments have been closed on this topic.



 

News


Also see my CRM Developer blog

Connect:              


Sponsor

Sections