Search code examples
javascriptpageloadclientscript

Set focus on an asp.net control on Page Load


I want to set focus on a control when page is loaded. I wrote this code but not working..

protected void setFocus(System.Web.UI.Control ctrl)
    {
        string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
        Type csType = this.GetType();
        ClientScript.RegisterStartupScript(csType, "focus", s);
    }

and this line in PageLoad method:

this.setFocus(txtHeightfeet);

Please help.

EDIT:

This is HTML:

<input name="ctl00$MainContent$txtHeightfeet" type="text" maxlength="2" id="MainContent_txtHeightfeet" class="textEntry2" style="width:65px;" />

This is aspx code:

<asp:TextBox ID="txtHeightfeet" runat="server" CssClass="textEntry2" MaxLength="2" Width="65"></asp:TextBox>&nbsp;ft&nbsp;

and in code behind cs file, i declared it the same as you have mentioned.


Solution

  • You should be able to just call the Focus() method of the control.

    No need for that Javascript.

    protected void Page_Load(object sender, EventArgs e)
    {
        txtHeightfeet.Focus(); 
    }