问题描述:

I am using AjaxControlToolkit version 4.1.40412.0, .NET 4.0, VS2010

Using the TabContainer control I want to add/remove tabs dynamically, but it looks like all of my dynamic changes are not persistent. Here is my scenario: I start with a tabcontainer with 1 tabpanel (hardcoded, i.e. added at design time), then dynamically I add more tabpanels and hide the original tabpanel (run time). As expected I see only the new tabpanels on the page, however any time I try to select a different tab the whole control reverts back to its design time state, i.e. only shows the original tabpanel, which was supposed to be gone and the new tabpanels are nowhere to be found. What am I missing? I guess as a workaround I can add 50 or so tabs at design time and then dynamically hide/display rather than remove/add, but this seems clunky, sloppy and unnecessary.

Here is my code if you want to duplicate the issue:

ASPX

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>

<asp:TabContainer ID="tcMain" runat="server" AutoPostBack="true" ScrollBars="auto" >

<asp:TabPanel ID="tbTab0" runat="server" HeaderText="Tab0"/>

</asp:TabContainer>

</div>

</form>

</body>

</html>

ASPX.VB

Public Class WebForm1

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Page.IsPostBack Then

For i As Integer = 0 To 3

Dim ol As New Label

ol.Text = i.ToString

Dim oT As New AjaxControlToolkit.TabPanel

oT.Controls.Add(ol)

oT.HeaderText = i.ToString

tcMain.Tabs.Add(oT)

Next

For i As Integer = 1 To tcMain.Tabs.Count

If tcMain.Tabs(tcMain.Tabs.Count - i).HeaderText = "Tab0" Then tcMain.Tabs.RemoveAt(tcMain.Tabs.Count - i)

Next

End If

End Sub

End Class

Note: If you comment out "If Not Page.IsPostBack Then" , i.e. run the code under it on every page load, the tabcontainer works as expected - I can select any tab without problems. In my real project this cannot be the solution though - I will be adding/removing tabs based on user input, so unless I keep a log of all changes ever made to the control I cannot load those changes every time the page loads.

网友答案:

You need to run your code in the page init or pre init, because by the page load, the page is already built along with the view state.

相关阅读:
Top