Click here to Skip to main content
Click here to Skip to main content

Automatically set control focus after ASP.NET AutoPostBack

, 28 Jun 2005
Rate this:
Please Sign up or sign in to vote.
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

About the Author

Simon McEnlly
Web Developer
Australia Australia
No Biography provided

Comments and Discussions

 
GeneralPerformance considerations PinmemberBen Lewies7-Sep-09 0:10 
Generalthanks.. Pinmemberbenyamin_202012-Jan-09 5:32 
GeneralProblem with datalist Edit mode Pinmemberecsmoore8-Mar-08 23:50 
QuestionProblem with Ajax Enabled Web page PinmemberCodeAli19-Sep-07 0:59 
Generalmove focus to next element Pinmemberanarayan13-Apr-06 5:53 
GeneralRe: move focus to next element PinmemberPeterB7226-Mar-07 3:34 
NewsRe: move focus to next element PinmemberHolger Schmid26-Apr-07 23:49 
GeneralRe: move focus to next element PinmemberMember 29997386-Dec-07 6:33 
GeneralRe: move focus to next element PinmemberMember 1021312615-Aug-13 23:48 
QuestionAdd Datalist and Datagrid controls Pinmemberviju874422-Nov-05 8:27 
AnswerRe: Add Datalist and Datagrid controls PinmemberSimon McEnlly22-Nov-05 22:48 
Questionhow to use in vb.net PinmemberJeff Kok10-Jul-05 2:06 
AnswerRe: how to use in vb.net PinmemberSimon McEnlly14-Jul-05 3:33 
GeneralSmartNavigation Pinmemberbryanallott5-Jul-05 23:27 
GeneralRe: SmartNavigation PinmemberSimon McEnlly6-Jul-05 3:15 
GeneralSomething different Pinmembernjappboy5-Jul-05 10:35 
GeneralRe: Something different [modified] PinmemberMember 29997386-Dec-07 6:51 
GeneralI think... a better version PinmemberDurlabh29-Jun-05 2:04 
GeneralRe: I think... a better version PinmemberSimon McEnlly29-Jun-05 3:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140718.1 | Last Updated 28 Jun 2005
Article Copyright 2005 by Simon McEnlly
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid