Set focus to a particular control on an ASP.NET web page

With a little JavaScript you can set the focus to a particular control on your ASP.NET web page. The sample code takes the control as a parameter, builds the JavaScript on the fly, then tells your ASPX page's code to send the JavaScript to the browser. To have your server code send the JavaScript to the client browser you use the RegisterStartupScript command. You can learn more about RegisterStartupScript by clicking here.

VB.NET code to catch and handle unhandled exceptions:

   Public Sub SetFocus(ByVal control As Control)
      If control.Page.IsStartupScriptRegistered("setFocus") Then
         Return
      End If

      Dim sb As StringBuilder = New StringBuilder("")

      control.Page.RegisterStartupScript("setFocus", sb.ToString())
   End Sub

Sample call to give the focus to a TextBox:

   SetFocus(txtText1)

About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page