Set the InitialFocus for an ASP.NET WebForm The PageUtil class has a static method SetInitialFocus(control) which can be used to generate a Javas cript for an ASP.NET page (WebForm), which sets the focus on a (given) control.
private void Page_Load(object sender, System.EventArgs e) { // Set the InitialFocus on TextBox1 PageUtil.SetInitialFocus(TextBox1);
using System; using System.Web.UI;
namespace InitialFocusDemo { /// <summary> /// Utility class for a ASP.NET page /// </summary> public class PageUtil {
/// <summary> /// Set the IntialFocus to the given control. Only works when Javas cript is supported. /// </summary> /// <param name="control">Control to set the InitialFocus on.</param> public static void SetInitialFocus(Control control) { if (control.Page == null) { throw new ArgumentException("The Control must be added to a Page before you can set the IntialFocus to it."); } if (control.Page.Request.Browser.Javas cript == true) { control.Page.RegisterClients criptBlock("InitialFocus", "<s cript FOR='window' EVENT='onload' LANGUAGE='Js cript'>document.all." + control.UniqueID + ".focus();</s cript>"); } }