Maintaining TabContainer active tab after postback from within the tabs (with AutoPostBack='false')
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 an开发者_StackOverflow中文版d 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.
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.
I got this from another forum. You set this in the pageload. I don't know if that would help with them being set to AutoPostBack=false, but if you haven't given up on it yet, I hope this helps
if (ViewState("ActiveTabIdx") != null)
{
activeTabIndex = Convert.ToInt32(ViewState("ActiveTabIdx"))
if (activeTabIndex != null)
{
TabContainer1.ActiveTabIndex = activeTabIndex;
}
}
you need to add ActiveTabChanged event for tab container and you can keep active tab index in view state, and on page load just check if it is not null then set it as Active tab index.
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
{
ViewState["ActiveTabIndex"] = TabContainer1.ActiveTabIndex;
}
PageOnLoad Event code
if (!(ViewState["ActiveTabIndex"] == null) )
{
TabContainer1.ActiveTabIndex = (int)ViewState["ActiveTabIndex"];
}
Make sure to add following attributes in TabContainer tag
AutoPostBack="true" OnActiveTabChanged="TabContainer1_ActiveTabChanged"
精彩评论