<%@ Page %>
Setting Initial Focus in Web Form
While designing ASP.NET web forms many times you require to set tab orders and focus of various controls. Tab orders are relatively easy as most of the web controls have a property called TabIndex. However, setting inital focus i.e. when page gets loaded for the first time in the browser window requires some coding. This article tells you how to get that done.
Consider that you have a web form that contains several textboxes. When the forms gets loaded in the browser window you want to take the cursor (focus) to the TextBox1. Here is how you can do that:
Page_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Public Shared Sub SetInitialFocus(ByVal ctrl As Control)
Dim s As StringBuilder = New StringBuilder()
Dim p As Control = ctrl.Parent
While Not TypeOf p Is System.Web.UI.HtmlControls.HtmlForm
p = p.Parent
s.Append("window.onload = SetInitialFocus;")
Now, let us dissect the code.
- The server side function SetInitialFocus is the heart of processing.
- We pass to this function a control instance (TextBox1 in our example) that is supposed to get initial focus.
- Obtaining control id is easy via ClientID property.
- However, to obtain form id we need to add the While loop that traverse the form control tree.
- Then we specify that this client side function should be called when window.onload event fires.
- Finally the RegisterClientScriptBlock method of the Page class is used to emit this script.
- This method accepts key (InitialFocus) and value (our function code) as its parameters. This also avoids duplicate script blocks based on the key supplied.
- You can pass controls to the server side SetInitialFocus method based on some logic.
I hope you found the article useful. See you soon!
is a software consultant, trainer, author, yoga mentor, and spiritual guide having 24+ years of experience in software development, consulting, and training. He conducts instructor-led online training courses
in ASP.NET Core, ASP.NET MVC, and Design Patterns for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga
to interested individuals. To know more about him click here
Get article updates : Facebook Twitter LinkedIn