Liran Friedman
Liran Friedman

Reputation: 4287

asp.net panel loses viewstate on postback

I have a web page with an update panel in it. Inside the update panel I have a panel with a user control like this:

<asp:UpdatePanel ID="updatePanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
    <asp:Panel ID="pnlFiles" runat="server" EnableViewState="true">
        <files:FilesControl runat="server" ID="filesControl" />
    </asp:Panel>
</ContentTemplate>

I have a list of checkboxes that whenever the user checks one of them I want to add another FilesControl to that panel so I am doing it like this:

FilesControl files = (FilesControl)LoadControl("~/UserControls/FilesControl.ascx");
files.ID = XXX;
pnlFiles.Controls.Add(files); 

But on every postback (every checkbox checked) the panel loses the last state and the controls added are wiped out, so the panel actually returns to its initial state every time and I can't ad more and more controls to it. I enabled view state and it didn't help. What am I missing out here ?

Upvotes: 0

Views: 1805

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460048

As requested, my comments as answer:

You need to add the control(s) to the page on every postback in Page_Init or Page_Load(at the latest) with the same ID as before.

The ID is unique, I generate it. I add the controls on the checkbox checked change event chkCompare_CheckedChanged

While it is perfectly fine to add a control dynamically in an event, it is necessary to re-create this control on the subsequent postbacks. That must be done in Page_Load at the latest (better: Page_Init). So you need to store somewhere which controls you have already added to be able to re-create them. Maybe it is sufficient to store the control-count in the ViewState.

So I should store the controls I added in the ViewState object and then re-add them to the panel on Page_Load ?

No, you shouldn't store the controls in the ViewState but the information that is necessary to re-create them. How do you know what you need to add? Of course you could also use a webdatabound control like Repeater, DataList or GridView where you only need to assign a DataSource and the persisting stuff is done automatically for you.

That is what is done with all controls even if you add them declaratively(on aspx). But those controls are re-created automatically by ASP.NET. All variables are disposed at the end of the page's life-cycle since the communication between the client and the server is stateless and disconnected.

Upvotes: 2

Related Questions