qt8gt0bxhw|20009F4EEE83|RyanMain|subtext_Content|Text|0xfbfff90000000000e000000001000c00
Setting focus to controls in your ASP.NET application is a part of giving your end users the feel that they have come to expect. Making your web applications act more like Windows applications is a key to success (IMO). While setting focus to controls is a very small part in achieving this, it does get you one step closer to having a polished web application that your users will love to use. It will be taken for granted, but something this small should be since it is expected behavior.
It is an easy task. It is accomplished in esstentially one line of Javascript. Adding common functionality to a utility class will go a long way in making this task even easier from your .NET web applications. The code below shows a static method that can be used to easily set focus to a control.
public static void SetFocus(Control control)
{
StringBuilder sb = new StringBuilder();
sb.Append("\r\n<script language='JavaScript'>\r\n");
sb.Append("<!--\r\n");
sb.Append("function SetFocus()\r\n");
sb.Append("{\r\n");
sb.Append("\tdocument.");
Control p = control.Parent;
while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;
sb.Append(p.ClientID);
sb.Append("['");
sb.Append(control.UniqueID);
sb.Append("'].focus();\r\n");
sb.Append("}\r\n");
sb.Append("window.onload = SetFocus;\r\n");
sb.Append("// -->\r\n");
sb.Append("</script>");
control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
}
The code results in adding Javascript to your page as follows:
<script language='JavaScript'>
<!--
function SetFocus()
{
document.Form1['TextBox1'].focus();
}
window.onload = SetFocus;
// -->
</script>
But you don't need to care about that because all you need to do to use it is call your static method from your code behind class:
PageUtility.SetFocus(TextBox1);
This will work from post-backs or from the page load.
Edit
I had some problems with the formatting of the code due to some angle brackets (caused most of the code to disappear). All fixed now. Sorry.