Maintaining TabContainer active tab after postback from within the tabs (with AutoPostBack='false')

David picture David · Jul 12, 2011 · Viewed 10.4k times · Source

I have an AjaxToolkit TabContainer control with a number TabPanels. Each TabPanel has a different UserControl in it to display some information. Some of these UserControls have either a LinkButton or a GridView with a command button in them. The TabContainer has AutoPostBack="false" and this is how I would like to keep it.

When you click on the LinkButton or command button in the GridView the expected events fire and the code runs. But when the page is returned the initial tab is selected again (and not the tab the user was previously viewing).

So my question is: Is there a way to maintain the selected tab when some child control causes a postback?

Some constraints:

  • I do not way to turn AutoPostBack on. This means the linked solution for this question question is no good in this case.
  • The UserControls are not always used in a TabContainer/TabPanel so the solution can not assume that this is the case.
  • The solution needs to be fairly robust and straightforward as there could be different devs working on this code.

Answer

AndyH picture AndyH · Jun 29, 2012

I solved this problem by creating my own control that inherits from TabContainer, then overriding LoadClientState() like this:

    protected override void LoadClientState(string clientState)
    {
        base.LoadClientState(clientState);

        // If post back was caused by control on a tab, make that tab the active one
        if (!string.IsNullOrEmpty(this.Page.Request.Params["__EVENTTARGET"]))
        {
            foreach (string ctlName in this.Page.Request.Params["__EVENTTARGET"].Split('$'))
            {
                if (this.FindControl(ctlName) is TabPanel && this.Tabs.Contains(this.FindControl(ctlName) as TabPanel))
                {
                    this.ActiveTab = (this.FindControl(ctlName) as TabPanel);
                    break;
                }
            }
        }
    }

This finds the TabPanel on which the control causing the postback resides, then makes that the active panel.