Click here to Skip to main content
Click here to Skip to main content

Retaining State for Dynamically Created Controls in ASP.NET applications

By , 18 Feb 2003
 

Introduction

When dynamically adding controls to an ASP.NET page in runtime the object references are lost at postback because they have no handle in the codebehind. The values entered by the user is not availible when accessing these objects after postback, and they seem empty. This article describes how to use ViewState to recreate and reinsert the postback values into the objects to access their values.

Background

An ASP.NET application with pages that use dynamic generation of controls that need to retain state across postbacks. The solution described in this paper enables you to create a totally dynamic number of controls at runtime and retreive their values after postback.

Solution

Dynamically added controls have no object reference variable in the codebehind class. They appear only in the control collection of the containing control, i.e. the Page.Controls collection. When the page is posted back to the server as a result of user interaction a new instance of the codebehind class is instantiated, and all the variables of the class is set with values from the ViewState.

This means that the objects we are accessing from the codebehind class, that "feels" like the same objects as we worked on before postback, actually are new ones that got their predecessors values via ViewState and ASP.NET state management.

So, the controls that were dynamically created are no longer there and consequently the values returned from these controls have no place to go. They are lost in the viewstate.

In order to catch these values the dynamically generated controls needs to be re-generated at Page_Load. The important thing is to assign the same ID to each control. The ViewState uses the ID property of the Control objects to reinstate the values.

Add the following elements to your System.UI.Page class:

public class DynamicallyAddingControls : System.Web.UI.Page
{
    // a Property that manages a counter stored in ViewState
    protected int NumberOfControls
    {
        get{return (int)ViewState["NumControls"];}
        set{ViewState["NumControls"] = value;}
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
        if(!Page.IsPostBack)
            //Initiate the counter of dynamically added controls
            this.NumberOfControls = 0;                
        else
            //Controls must be repeatedly be created on postback
            this.createControls();
    }

    // This routine creates the controls and assigns a generic ID
    private void createControls()
    {
        int count = this.NumberOfControls;

        for(int i = 0; i < count; i++)
        {
            TextBox tx = new TextBox();
            tx.ID = "ControlID_" + i.ToString();
            //Add the Controls to the container of your choice
            Page.Controls.Add(tx);
        }
    }

    // example of dynamic addition of controls
    // note the use of the ViewState variable
    private void addSomeControl()
    {
        TextBox tx = new TextBox();
        tx.ID = "ControlID_" + NumberOfControls.ToString();

        Page.Controls.Add(tx);
        this.NumberOfControls++;
    }

}

Note that the createControls method has to simulate the way that you dynamically built your page before the postback. The important thing here is obviously to assign identical ID values to the correct type of controls to that we can access them at postback.

Points of Interest

This solution works because the ASP.NET ViewState supports dynamically added controls, but does not do the re-generation for us. As long as the ID properties match ASP.NET does the rest of the job for us.

Thanks to Eric Sütter for providing valuable input on this article!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mads Nissen
Software Developer (Senior)
Norway Norway
Member
http://weblogs.asp.net/mnissen
http://www.puzzlepart.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionUse the DynamicControlsPlaceholder to save its child-controlsmemberMr. Truong Pham28 Mar '13 - 5:09 
QuestionHow to Maintain state for the data availabel in the TextBoxesmemberMember 93911892 Dec '12 - 15:06 
GeneralCorrectionsmemberBrightSoul12 Dec '10 - 4:46 
GeneralMy vote of 5memberpravin4work26 Sep '10 - 23:55 
GeneralMy vote of 5memberbigbulldawg14 Aug '10 - 15:31 
Generalgives me this kindof error...memberzazabzulla31 Aug '09 - 2:58 
Generalokey how about thismemberArash Javadi27 May '09 - 3:20 
GeneralGenerate conditional dynamic controls and save view statememberMember 323276614 Feb '09 - 22:26 
GeneralErrormemberD. PAUL5 Aug '08 - 20:10 
Questionhow can i get checkbox values in gridview that i inserted them dynamically?memberMojtaba Madadyar14 Jun '08 - 10:09 
GeneralControl values are lost after post back !!!memberadhamzzz1 Jul '06 - 22:06 
QuestionCan't get value after postbackmemberGundamrx7819 May '06 - 4:54 
AnswerRe: Can't get value after postbackmembersaswata.purkayastha@gmail.com28 Dec '06 - 20:05 
GeneralRe: Can't get value after postbackmemberDiskJunky1 Aug '07 - 23:43 
GeneralRe: Can't get value after postbackmemberjugomkd17 Apr '08 - 23:50 
Questionhow to use find control in table???memberembeded25 Dec '05 - 15:19 
GeneralAcess Data for update, insert, ...memberVitor Hugo Barros19 Jul '05 - 10:59 
GeneralRe: Acess Data for update, insert, ...membersmair30 Aug '05 - 22:16 
GeneralRe: Acess Data for update, insert, ...memberVitor Hugo Barros31 Aug '05 - 4:39 
GeneralRe: Acess Data for update, insert, ...memberRB@Emphasys7 Sep '06 - 10:23 
Generalfind control of placeholder,pls help:-)sussAnonymous19 Jul '05 - 8:38 
GeneralLabel problemmemberbiktor817 Jun '05 - 6:15 
GeneralRe: Label problemsussMarcTH25 Jul '05 - 23:41 
GeneralRe: Label problemmembersmair30 Aug '05 - 22:20 
GeneralMaintain state with linkbuttonmemberkannadasan9 Sep '04 - 22:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 19 Feb 2003
Article Copyright 2003 by Mads Nissen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid