.NET流水账

一个真正的开明进步的国家,不是一群奴才造成的,是要有独立个性,有自由思考的人造成的。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  17 随笔 :: 0 文章 :: 30 评论 :: 29606 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

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

下面是用到的JavaScript代码。 

1<script language="javascript"> 
2  var control = document.getElementById(<control name>); 
3  if( control != null ){ control.focus(); } 
4</script> 
 
这里写了一个SetFocusControl函数来封装上面的JavaScript代码,并且注册到页面上,注册到页面上使用的是Page.RegisterStartupScript 方法  

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


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

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

1Private Sub SetFocus(ByVal controlToFocus As Control)
 
2    Dim scriptFunction As New StringBuilder
 
3    Dim scriptClientId As String
 
4    scriptClientId = controlToFocus.ClientID
 
5    scriptFunction.Append("<script language='javascript'>")
 
6    scriptFunction.Append("document.getElementById('" & scriptClientId & "').focus();")
 
7    scriptFunction.Append("</script>")
 
8    RegisterStartupScript("focus",   scriptFunction.ToString())
 9
End Sub

10
11
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
12    If (Page.IsPostBack = FalseThen
13        SetFocus(TextBox1)
14    End If
15
End Sub
 
16

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

1Private  Function SetFocus(ByVal controlToFocus As Control) As String 
 
2   ' The SetFocusScript method set focus to a control on a page load 
 3   Dim sb As New StringBuilder  
 
4   sb.Append(" <SCRIPT language='javascript'>")  
 
5   sb.Append("document.getElementById('")  
 
6   sb.Append(controlToFocus.ClientID) 
 
7   sb.Append("').focus();</SCRIPT> "
 
8   If Not Page.IsStartupScriptRegistered("focus"Then 
 
9      Page.RegisterStartupScript("focus", sb.ToString()) 
10   End If 
11
End Function

In Page_Load:

1Me.SetFocus(Me.txtUserName)

 

posted on   DalianGary  阅读(1492)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示