1

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.

asma
  • 2,795
  • 13
  • 60
  • 87
  • possible duplicate of [Set focus to textbox in ASP.NET Login control on page load](http://stackoverflow.com/questions/3043592/set-focus-to-textbox-in-asp-net-login-control-on-page-load) – David d C e Freitas Oct 25 '13 at 01:12

1 Answers1

3

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(); 
}
Mark Biek
  • 146,731
  • 54
  • 156
  • 201