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

    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
    Water Cooler v2, Aug 17, 2005
    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>";

    Hope this helps.
    Home :
    Blog :
    Web :

    "Any one who has never made a mistake has never tried anything new" - Einstein
    Guest, Aug 17, 2005
    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 & _

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

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

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


    Jan 13, 2011
    Likes Received:

    just add into the Page-Load function the following:


    works for me.. cheers!

    drujba, Jan 13, 2011
    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.