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> ft
and in code behind cs file, i declared it the same as you have mentioned.
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> ft
and in code behind cs file, i declared it the same as you have mentioned.
Share Improve this question edited May 4, 2011 at 12:21 asma asked May 4, 2011 at 10:16 asmaasma 2,85516 gold badges64 silver badges88 bronze badges 1- possible duplicate of Set focus to textbox in ASP.NET Login control on page load – David d C e Freitas Commented Oct 25, 2013 at 1:12
1 Answer
Reset to default 3You 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();
}