Kriya and Meditation for Software / IT Professionals. Conducted by Bipin Joshi in Thane. Read more...
Learn ASP.NET MVC, ASP.NET Core and ASP.NET Design Patterns. Courses conducted by Bipin Joshi on weekends. Click here for more details.

<%@ Page %>

Setting Initial Focus in Web Form

Introduction

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.

JavaScript to rescue

Many beginners feel that ASP.NET and client side scripts can not be used together. If used cleverly they can go hand in hand to give great user experience. The above task of setting initial focus can be easily solved by JavaScript. We can certainly write the entire javascript block at design time in the .aspx file itself but then you should already know which control to give focus. There is still flexible way to do this. In next sections we will see this with an example.

Example

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:
Private Sub 
Page_Load(ByVal sender As System.Object, 
ByVal e As System.EventArgs) 
Handles MyBase.Load

 SetInitialFocus(TextBox1)
End Sub

Public Shared Sub SetInitialFocus(ByVal ctrl As Control)
Dim s As StringBuilder = New StringBuilder()
s.Append("<SCRIPT LANGUAGE='JavaScript'>")
s.Append("function SetInitialFocus()")
s.Append("{")
s.Append("   document.")

Dim p As Control = ctrl.Parent
While Not TypeOf p Is System.Web.UI.HtmlControls.HtmlForm
	p = p.Parent
End While
s.Append(p.ClientID)
s.Append("['")
s.Append(ctrl.UniqueID)
s.Append("'].focus();")
s.Append("}")
s.Append("window.onload = SetInitialFocus;")
s.Append("</SCRIPT>")
ctrl.Page.RegisterClientScriptBlock("InitialFocus", s.ToString())
End Sub

Explanation

Now, let us dissect the code.
  • The server side function SetInitialFocus is the heart of processing.
  • This function generates a client side javascript function called SetInitialFocus.
  • We pass to this function a control instance (TextBox1 in our example) that is supposed to get initial focus.
  • In JavaScript we need to know the form id and the control id in order to fire scripts against them.
  • 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!


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. 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 Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 14 June 2002


Tags : ASP.NET Web Forms