2011-05-04 78 views
1

我想在加載頁面時將焦點設置在控件上。 我寫了這個代碼,但沒有工作..設置焦點在頁面加載的asp.net控件

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); 
    } 

這行pageLoad的方法:

this.setFocus(txtHeightfeet); 

請幫助。

編輯:

這是HTML:

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

這是ASPX代碼:

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

,並在後面的CS文件中的代碼,我宣佈它同你提到。

+0

[將焦點設置爲ASP.NET頁面加載時的ASP.NET登錄控件中的文本框]的可能重複(http://stackoverflow.com/questions/3043592/set-focus-to-textbox-in-asp-net -login-control-on-load) – 2013-10-25 01:12:53

回答

3

您應該可以直接調用Focus()控件的方法。

不需要該Javascript。

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

我用過這個,但不工作 – asma 2011-05-04 10:43:45

+0

你可以發佈txtHeightfeet的HTML標記,以及你如何在代碼隱藏中聲明它? – 2011-05-04 11:58:49

+0

請看我更新的帖子 – asma 2011-05-04 12:21:49