在Windows应用程序中很容易控制控件的聚焦,但是在ASP.NET中并没有提供这样的功能,但是我们同样可以实现这样的功能,下面是本人整理的三种类似的方法,供大家参考。

方法1:设置服务器端控件的焦点

下面是用到的JavaScript代码。 

1Set Focus to Web Control<script language="javascript"> 
2Set Focus to Web Control  var control = document.getElementById(<control name>); 
3 
 
这里写了一个SetFocusControl函数来封装上面的JavaScript代码,并且注册到页面上,注册到页面上使用的是Page.RegisterStartupScript 方法  

Set Focus to Web Control1Public Sub SetFocusControl(ByVal ControlName As String) 
Set Focus to Web Control 
2        ' character 34 = "                   
Set Focus to Web Control
 3        ' 注意空格的书写这里用chr(34) 
Set Focus to Web Control
 4        Dim script As String = _ 
Set Focus to Web Control 
5          "<script language=" + Chr(34+ "javascript" + Chr(34) _ 
Set Focus to Web Control 
6                             + ">" + _ 
Set Focus to Web Control 
7          "  var control = document.getElementById(" + Chr(34+ _ 
Set Focus to Web Control 
8          ControlName + Chr(34+ ");" + _ 
Set Focus to Web Control 
9          "  if( control != null ){control.focus();}" + _ 
Set Focus to Web Control
10          "</script>" 
Set Focus to Web Control
11        Page.RegisterStartupScript("Focus", script) 
Set Focus to Web Control12End Sub 
Set Focus to Web Control
   


其中的ControlName是你要获得焦点的控件的ID。
------------------------------------------------------------------------

方法2: 设置服务器端控件的焦点

16

方法3:设置服务器端控件的焦点

End Function

In Page_Load:

1Set Focus to Web ControlMe.SetFocus(Me.txtUserName)

 

相关文章: