Tuesday, January 8, 2008

Setting Focus in ASP.NET User Control

When using an ASP.NET user control, there is no tag to set a Javascript event handler for calling a function to set focus to a control. One solution I found was to write a public utility method that accepts a control as an argument, and dynamically builds the Javascript function to set focus to that specific control.

1. Create a public utility class in App_Code containing a public method named "SetFocus":


using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public class PageUtils
{
public static void SetFocus(Control control)
{
StringBuilder sb = new StringBuilder();
sb.Append("\r\n
");

control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
}
}


2. Call the above method in the code-behind of the user control's page loading/rendering method passing the control that requires initial focus:

PageUtils.SetFocus(this.txtSearchField);

No comments: