It is well-documented that Windows Forms more easily can provide a better user experience and Web Forms offer greater flexibility in deployment. Often, developers are tasked with reconciling these two unique features into a single Web application.
Because Web applications are generally stateless, it takes some extra effort to offer some of the convenience of a Windows Forms application. Web controls do not support the focus behavior in the code behind but a client-side script does. This article demonstrates one technique for refocusing the previous control after a postback.
Writing Code to Statically Focus a Control
Simple Web applications with static content seldom need any cleverness (or much code, for that matter). However, when programmers write complex applications that have pages that contain a lot of controls, keeping track of user activity and facilitating data input can be highly important.
For example, if one is writing applications that are especially geared toward "heads-down data entry," reducing the number of extra steps can make a big difference in productivity.
Let's begin by looking at the static script necessary to focus a control and then we'll convert this script to a dynamically rendered version.
Listing 1 demonstrates a static script block that focuses the same control every time. Startup script is a block of script that is placed within the <form> tag and is run as the page is loaded.
Listing 1 Static Script to Refocus the TextBoxAddress Control When a Page is Rendered.
The script requests the control by its object name. If the control was successfully found and returned, the control.focus() method is called.