写了一个SetFocusControl函数来封装上面的JavaScript代码,并且注册到页面上,注册到页面上使用的是Page.RegisterStartupScript 方法
Public Sub SetFocusControl()Sub SetFocusControl(ByVal ControlName As String)
' character 34 = "
' 注意空格的书写这里用chr(34)
Dim script As String = _
"<script language=" + Chr(34) + "javascript" + Chr(34) _
+ ">" + _
" var control = document.getElementById(" + Chr(34) + _
ControlName + Chr(34) + ");" + _
" if( control != null ){control.focus();}" + _
"</script>"
Page.RegisterStartupScript("Focus", script)
End Sub
' character 34 = "
' 注意空格的书写这里用chr(34)
Dim script As String = _
"<script language=" + Chr(34) + "javascript" + Chr(34) _
+ ">" + _
" var control = document.getElementById(" + Chr(34) + _
ControlName + Chr(34) + ");" + _
" if( control != null ){control.focus();}" + _
"</script>"
Page.RegisterStartupScript("Focus", script)
End Sub
其中的ControlName是你要获得焦点的控件的ID。
一个实例部分代码
.....
public class _05_01_13 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.Button Button3;
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.TextBox TextBox2;
protected System.Web.UI.WebControls.Button Button4;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
///
/// 设置光标位置
///
///
///
public static bool SetFocus(System.Web.UI.Control control)
{
if (HttpContext.Current.Request.Browser.JavaScript)
{
control.Page.RegisterStartupScript("sf"," ");
return true;
}
return false;
}
{
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.Button Button3;
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.TextBox TextBox2;
protected System.Web.UI.WebControls.Button Button4;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
///
/// 设置光标位置
///
///
///
public static bool SetFocus(System.Web.UI.Control control)
{
if (HttpContext.Current.Request.Browser.JavaScript)
{
control.Page.RegisterStartupScript("sf"," ");
return true;
}
return false;
}
private void Button1_Click(object sender, System.EventArgs e)
{
//让TextBox1获得焦点
SetFocus(TextBox1);
}