Problem with dynamic controls in .NET Problem with dynamic controls in .NET asp.net asp.net

Problem with dynamic controls in .NET


ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that:

ViewState propeties set during the Init event are not backed to ViewState (because the Page has not yet started tracking ViewState). Thus Init is a good place to add controls and set (a) properties that won't change between postbacks (ID, CssClass...) as well as initial values for dynamic properties (which can then be modified by code in the rest of the page lifecycle - Load, event handlers, PreRender).

When dynamically adding controls in Load or PreRender, ViewState is being tracked. The developer can then control which propeties are persisted for dynamically added controls as follows:

  • Properties set before the control is added to the page's control tree are not persisted to ViewState. You typically set properties that are not dynamic (ID etc) before adding a control to the control tree.

  • Properties set after the control is added to the page's control tree are persisted to ViewState (ViewState tracking is enabled from before the Load Event to after the PreRender event).

In your case, your PreRender handler is setting properties before adding the control to the page's control tree. To get the result you want, set dynamic properties after adding the control to the control tree: .

protected override void OnPreRender(EventArgs e){    base.OnPreRender(e);    ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2]            tempLink.ID = "valueLinkButton"; // Not persisted to ViewState    Controls.Clear();    Controls.Add(tempLink);    tempLink.Value = "new value";  // Persisted to ViewState    tempLink.Text = "Click";       // Persisted to ViewState}


As others have statement you'll need to ensure that you are creating via the Init method. To learn more about the ASP.NET page life cycle check out this article: http://msdn.microsoft.com/en-us/library/ms178472.aspx


I'm already re-creating the controls in my OnLoad event.

That's your problem. OnLoad is too late. Use Init instead.