Set Focus After Postback
To set the focus on a certain control after a page postback, we can either add a dynamic script javascript block; or set the SmartNavigation attribute to true in the @ Page directive in the .aspx file.
SmartNavigation is only supported by IE 5.5 browser, or later. It resets the focus and scroll position between post back, and the user won't feel the whole screen flickering. However, it is said that from time to time it is not smart enough to cooperate well with javascript and CSS-Styles. Anyway, if your code runs only on IE and is not too complex, SmartNavigation is quite cute to use.
The following is the JavaScript way. The supposed scenario is, there are two dropdownlists, ddlCountry and ddlProvState. the autopostback porperty of ddlCountry is set to true; as a result, when the selected value is changed, a postback happens, and ddlProvState is bound to a new datasource and get the focus.
Step 1 - Declare variables in class
protected string Focus = "";
protected string ControlType = "";
Step 2 - Event Handler
private void ddlCountry_SelectedIndexChanged(object sender, System.EventArgs e)
{
Focus = "ddlProvState";
ControlType = "DropDownList";
}
Step 3 - The javascirpt block
<script language="javascript">
var o = document.getElementById("<%= Focus %>");
if (o != null) o.focus();
if("<%= ControlType %>" == "TextArea") document.all["<%= Focus %>"].select();
</script>
We can embed above javascript in the HTML portion of the aspx page (not the code behind), before the the closing </form> tag. It would work fine.
Of course, we also can implement it through code behind by a method,
private void CSBSetFocus()
{
string strJS;
strJS="<script language='javascript'>" +
"var o = document.getElementById('" + Focus.ToString() +"'); " +
"if (o != null) o.focus(); " +
"if('" + ControlType.ToString() + "' == 'TextArea') " +
"document.all['" + Focus.ToString() +"'].select(); " +
"</script>";
Page.RegisterStartupScript("CSB-focus-function", strJS);
}
Step 4 - Call the method
private void Page_PreRender(object sender, System.EventArgs e)
{
CSBSetFocus();
}
Done!
This works in both ASP.NET 1.0 and 2.0. For ASP.NET 2.0, there are other methods to maintain the focus after postback. We’ll discuss that another time.