Set focus to a textbox on page load

Discussion in 'ASP .Net' started by Water Cooler v2, Aug 17, 2005.

  1. I am new to ASP/ASP.NET so kindly be gentle. When my index.aspx page
    loads, I need the focus to be on one of the textboxes called
    txtUserName.

    I come from a VB background, so expecting the obvious, I go to the
    Page_Load event of the index.aspx page and try to write
    txtUserName.SetFocus but I see there isn't a SetFocus method for the
    System.Web.UI.WebControls.TextBox class.

    What's the way to set the focus to a textbox on the page load in
    ASP.NET?
     
    Water Cooler v2, Aug 17, 2005
    #1
    1. Advertisements

  2. Water Cooler v2

    Guest Guest

    you can write a function something like this and use it when u need them.

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

    Hope this helps.
    --
    Kannan.V
    Home : http://www.kannanv.com
    Blog : http://kannanv.blogspot.com
    Web : http://www.DotnetLounge.net

    "Any one who has never made a mistake has never tried anything new" - Einstein
     
    Guest, Aug 17, 2005
    #2
    1. Advertisements

  3. As the last post adviced this should do the trick:-

    Private Sub SetFocus(ByVal ctrl As Control)
    ' Define the JavaScript function for the specified control.
    Dim focusScript As String = "<script language='javascript'>" & _
    "document.getElementById('" + ctrl.ClientID & _
    "').focus();</script>"

    ' Add the JavaScript code to the page.
    Page.RegisterStartupScript("FocusScript", focusScript)
    End Sub

    Hope this helps
    Patrick
     
    Patrick Olurotimi Ige, Aug 17, 2005
    #3
  4. It's a client-side task. You need to call javascript focus() method on the
    element you want to set focus on.

    Eliyahu
     
    Eliyahu Goldin, Aug 17, 2005
    #4
  5. Water Cooler v2

    drujba

    Joined:
    Jan 13, 2011
    Messages:
    1
    Likes Received:
    0
    focus

    just add into the Page-Load function the following:

    txUserName.Focus();

    works for me.. cheers!



     
    drujba, Jan 13, 2011
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.