<%@ 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!