Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Automatically set control focus after ASP.NET AutoPostBack

0.00/5 (No votes)
28 Jun 2005 4  
Automatically set control focus after ASP.NET AutoPostBack.

Introduction

Wouldn't it be nice if ASP.NET managed setting the focus of web controls after autopostback? This article will show you a fairly effortless way of achieving this.

The Solution

  1. Download the source code above and compile it.
  2. Include the built assembly as a reference on your ASP.NET solution.
  3. In your ASP.NET code-behind file, you will see a line that looks like this:
     public class WebForm1 : System.Web.UI.Page
     {

    Change this to:

     public class WebForm1 : WebControls.Page
     {
  4. Test your ASP.NET solution. You'll find that when your controls auto-postback, they now set focus back to themselves when the page is reloaded.

How does this work?

The way the code works is that it inherits the System.Web.UI.Page class and overrides two key methods:

  • OnInit()
  • OnPreRender()

When the page is initialized, it searches recursively for any controls that are of a specific type (see code below). If it finds these controls, it adds the event handler that is called during autopostback. When the event is fired, it sets the focus control to the event sender.

During the pre-render, if a control has been set to get focus on load, then JavaScript is written to the client to automatically set focus to the control.

The new Page class also has a mechanism for setting focus at any time during its life-cycle. (For e.g., on Page_Load, a default control may be given the initial focus.)

public class Page : System.Web.UI.Page 
{
    internal System.Web.UI.WebControls.WebControl setFocusControl = null;

    private void LoadControlEvents(System.Web.UI.ControlCollection controls)
    {
        foreach (System.Web.UI.Control control in controls)
        {
            if (control.Controls != null)
                LoadControlEvents(control.Controls);

            if (control is TextBox)
            {
                ((TextBox)control).TextChanged += 
                       new EventHandler(Control_Event);
            }
            else if (control is Button)
            {
                ((Button)control).Click += new EventHandler(Control_Event);
            }
            else if (control is LinkButton)
            {
                ((LinkButton)control).Click += 
                        new EventHandler(Control_Event);
            }
            else if (control is ImageButton)
            {
                ((ImageButton)control).Click += new 
                  System.Web.UI.ImageClickEventHandler(ImageButtonHandler);
            }
            else if (control is DropDownList)
            {
                ((DropDownList)control).SelectedIndexChanged += 
                               new EventHandler(Control_Event);
            }
            else if (control is ListBox)
            {
                ((ListBox)control).SelectedIndexChanged += 
                          new EventHandler(Control_Event);
            }
            else if (control is CheckBox)
            {
                ((CheckBox)control).CheckedChanged += 
                      new EventHandler(Control_Event);
            }
            else if (control is CheckBoxList)
            {
                //Not Tested

                ((CheckBoxList)control).SelectedIndexChanged += 
                               new EventHandler(Control_Event);
            }
            else if (control is RadioButton)
            {
                //Not Tested

                ((RadioButton)control).CheckedChanged += 
                        new EventHandler(Control_Event);
            }
            else if (control is RadioButtonList)
            {
                //Not Tested

                ((RadioButtonList)control).SelectedIndexChanged += 
                                  new EventHandler(Control_Event);
            }
            else if (control is Calendar)
            {
                //Not Tested

                ((Calendar)control).SelectionChanged += 
                       new EventHandler(Control_Event);
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        LoadControlEvents(this.Controls);

        base.OnInit (e);
    }

    private void Control_Event(object sender, System.EventArgs e)
    {
        SetFocusControl(sender);
    }

    private void ImageButtonHandler(object sender, 
                      System.Web.UI.ImageClickEventArgs e)
    {
        SetFocusControl(sender);
    }

    private void SetFocusControl(object sender)
    {
        if ((setFocusControl == null) && 
                 (sender is System.Web.UI.WebControls.WebControl))
            setFocusControl = (System.Web.UI.WebControls.WebControl)sender;
    }

    public void SetFocus(System.Web.UI.WebControls.WebControl control)
    {
        setFocusControl = control;
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender (e);

        //Setfocus script

        if ((setFocusControl != null) && 
                 (!this.IsStartupScriptRegistered("SetControlFocus")))
            this.RegisterStartupScript(
                "SetControlFocus", 
                string.Format("<script language="'\""JavaScript\"'>document" + 
                              ".getElementById('{0}').focus();</script>", 
                              setFocusControl.ClientID));
    }
}

Points to Consider

This same code should work with any page that has inherited from the base System.Web.UI.WebControls. The code above may also be modified to set focus to any custom control.

I have not tested this code in browsers other than IE 6.0 but I would imagine that any problems should be easily fixed with modifications to the generated JavaScript.

Please email me any enhancements that you make to this class and I will keep this article updated.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here