Click here to Skip to main content
11,581,982 members (78,207 online)
Click here to Skip to main content

Maintain focus between postbacks in ASP.NET 2.0, also in ASP.NET AJAX

, 8 Feb 2007 CPOL 195.2K 2.2K 56
Rate this:
Please Sign up or sign in to vote.
A workaround to maintain focus between postbacks in ASP.NET 2.0, also in ASP.NET AJAX without SmartNavigation.

The Problem

Let's assume you have two TextBoxes. The first one has a TextChanged event attached and AutoPostBack set to true. When you edit TextBox1 and move to TextBox2, the control TextBox2 loses its focus.

Case 1: The normal postback in ASP.NET 2.0 without smart navigation.

The trick is to save the name of the control which received focus at last, and then restore it after postback. There is a hidden field __LASTFOCUS, and we are going to use it.

First of all, let us go through all "relevant" controls and set the attribute onfocus to save their name when they receive focus. "Relevant" are controls which potentially can receive focus. Because we do not want to set this attribute to each control explicitly, we just define types of "relevant" controls and enumerate them recursively.

protected void Page_Load(object sender, EventArgs e)
{
     //sets onfocus event to all apropriate controls on the page.
     if (!IsPostBack)
          HookOnFocus(this.Page as Control);
}
/// <span class="code-SummaryComment"><summary>
</span>
/// This function goes recursively all child controls and sets 
/// onfocus attribute if the control has one of defined types.
/// <span class="code-SummaryComment"></summary>
</span>
/// <span class="code-SummaryComment"><param name="CurrentControl">the control to hook.</param>
</span>
private void HookOnFocus(Control CurrentControl)
{
    //checks if control is one of TextBox, DropDownList, ListBox or Button
    if ((CurrentControl is TextBox) ||
        (CurrentControl is DropDownList) ||
        (CurrentControl is ListBox) ||
        (CurrentControl is Button))
    //adds a script which saves active control on receiving focus 
    //in the hidden field __LASTFOCUS.
        (CurrentControl as WebControl).Attributes.Add(
           "onfocus",
           "try{document.getElementById('__LASTFOCUS').value=this.id} 
               catch(e) {}");
        //checks if the control has children
        if (CurrentControl.HasControls())
            //if yes do them all recursively
            foreach (Control CurrentChildControl in CurrentControl.Controls)
                HookOnFocus(CurrentChildControl);
}

Add aditional control types in the first if condition under the function private void HookOnFocus(Control CurrentControl).

Now, we need to set focus after the postback. Insert the following JavaScript as a constant in your page:

/// <span class="code-SummaryComment"><summary>
</span>
/// This script sets a focus to the control with a name to which
/// REQUEST_LASTFOCUS was replaced. Setting focus heppens after the page
/// (or update panel) was rendered. To delay setting focus the function
/// window.setTimeout() will be used.
/// <span class="code-SummaryComment"></summary>
</span>
private const string SCRIPT_DOFOCUS =
    @"window.setTimeout('DoFocus()', 1);
    function DoFocus()
    {
        try {
            document.getElementById('REQUEST_LASTFOCUS').focus();
        } catch (ex) {}
    }";

and this statement to Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    //sets onfocus event to all apropriate controls on the page.
    if (!IsPostBack)
        HookOnFocus(this.Page as Control);

    //replaces REQUEST_LASTFOCUS in SCRIPT_DOFOCUS with 
    //the posted value from Request    
    //["__LASTFOCUS"]
    //and registers the script to start after the page was rendered
    Page.ClientScript.RegisterStartupScript(
        typeof(MyPage),
        "ScriptDoFocus",
        SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", 
                               Request["__LASTFOCUS"]),
        true);
}

Case 2: A "tiny Postback" inside the UpdatePanel in ASP.NET 2.0 AJAX

The only difference is that setting the focus must happen after each update inside UpdatePanel. In this case, the script registered using Page.ClientScript.RegisterStartupScript() will execute only after each global postback. We need to use ScriptManager.RegisterStartupScript() instead. The Page_Load will look like this:

protected void Page_Load(object sender, EventArgs e)
{
    //sets onfocus event to all apropriate controls on the page.
    if (!IsPostBack)
            HookOnFocus(this.Page as Control);

    //replaces REQUEST_LASTFOCUS in SCRIPT_DOFOCUS with the posted value from 
    //Request ["__LASTFOCUS"]
    //and registers the script to start after Update panel was rendered
    ScriptManager.RegisterStartupScript(
        this,
        typeof(MyPage),
        "ScriptDoFocus",
        SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", Request["__LASTFOCUS"]),
        true);
}

Links

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

George Mamaladze
Software Developer
Germany Germany
Tweeter: @gmamaladze
Google+: gmamaladze
Blog: gmamaladze.wordpress.com

You may also be interested in...

Comments and Discussions

 
QuestionChange focus to next cell after postback Pin
Sandip Paul 49198412-May-14 8:35
memberSandip Paul 49198412-May-14 8:35 
BugGetting error when trying to add code Pin
Datta Salunkhe11-Apr-14 0:17
memberDatta Salunkhe11-Apr-14 0:17 
QuestionNot Working On Page Scroll Pin
Abu Noumaan20-Mar-13 22:27
memberAbu Noumaan20-Mar-13 22:27 
Questionclicking on links Pin
m0dest019-Dec-12 8:52
memberm0dest019-Dec-12 8:52 
GeneralMy vote of 5 Pin
m0dest018-Dec-12 7:28
memberm0dest018-Dec-12 7:28 
QuestionHow can you modify this code to retain focus on F5 Refresh as well as postback? Pin
sarndt22-Feb-12 9:49
membersarndt22-Feb-12 9:49 
QuestionFor some reason it is not working.... using vb.net Pin
Member 779716719-Jan-12 13:08
memberMember 779716719-Jan-12 13:08 
GeneralMy vote of 5 Pin
reSPAWNed868-Dec-11 0:24
memberreSPAWNed868-Dec-11 0:24 
QuestionDoes Not work with repeater ! please help !! Pin
jashlubana7-Sep-11 10:21
memberjashlubana7-Sep-11 10:21 
AnswerRe: Does Not work with repeater ! please help !! Pin
Alexsander Antunes14-Nov-11 6:31
memberAlexsander Antunes14-Nov-11 6:31 
QuestionCan't you simple set MaintainScrollPositionOnPostback to "true" ? Pin
Fedor Steeman29-Mar-11 2:45
memberFedor Steeman29-Mar-11 2:45 
AnswerRe: Can't you simple set MaintainScrollPositionOnPostback to "true" ? Pin
jeff_wong7-Jul-11 16:19
memberjeff_wong7-Jul-11 16:19 
GeneralUse with Master Pages Pin
Rebecca Caudill21-Jan-10 5:04
memberRebecca Caudill21-Jan-10 5:04 
GeneralProblem when client id changes Pin
stesson10-May-09 22:31
memberstesson10-May-09 22:31 
Generalvalue vs Value Pin
RobinT7721-Apr-09 1:20
memberRobinT7721-Apr-09 1:20 
GeneralDoes not work with span's Pin
Rob van Rijen14-Jul-08 5:45
memberRob van Rijen14-Jul-08 5:45 
GeneralI found a compilation error Pin
Martin Neu5-Jun-08 4:20
memberMartin Neu5-Jun-08 4:20 
AnswerRe: I found a compilation error Pin
Mr MM23-Jun-08 7:19
memberMr MM23-Jun-08 7:19 
GeneralDetermining AJAX or NON-AJAX Pin
Member 477649823-Apr-08 10:57
memberMember 477649823-Apr-08 10:57 
Generaldinamic controls or only in a few controls. [modified] Pin
Member 413759610-Mar-08 6:03
memberMember 413759610-Mar-08 6:03 
QuestionCan be use for FocusOnError() Pin
mdsahni9-Mar-08 4:01
membermdsahni9-Mar-08 4:01 
GeneralUser Controls lost focus with ajax.net Pin
Roni Peterson19-Dec-07 9:55
memberRoni Peterson19-Dec-07 9:55 
GeneralMasterpages with Updatepanel (.Net 3.5) [modified] Pin
DUMITRU Guraliuc11-Dec-07 23:06
memberDUMITRU Guraliuc11-Dec-07 23:06 
QuestionAjax Problem Pin
Saad Alam31-Aug-07 4:53
memberSaad Alam31-Aug-07 4:53 
GeneralshowModalDialog Pin
johndhunter23-May-07 5:46
memberjohndhunter23-May-07 5:46 

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 | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 9 Feb 2007
Article Copyright 2007 by George Mamaladze
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid