Click here to Skip to main content
11,923,948 members (60,542 online)
Click here to Skip to main content
Add your own
alternative version


89 bookmarked

Retaining State for Dynamically Created Controls in ASP.NET applications

, 18 Feb 2003
Rate this:
Please Sign up or sign in to vote.
When creating controls on the fly on your ASP.NET pages viewstate is a bit hard to track. Learn how it works and how to help your application remembers where to put what.


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.


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.


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)
            //Initiate the counter of dynamically added controls
            this.NumberOfControls = 0;                
            //Controls must be repeatedly be created on postback

    // 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

    // 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();



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!


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

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
pedroestrada29-Jan-14 1:00
memberpedroestrada29-Jan-14 1:00 
QuestionTextboxes null Pin
yogen@softyoug16-Dec-13 20:44
memberyogen@softyoug16-Dec-13 20:44 
QuestionUse the DynamicControlsPlaceholder to save its child-controls Pin
Mr. Truong Pham28-Mar-13 6:09
memberMr. Truong Pham28-Mar-13 6:09 
QuestionHow to Maintain state for the data availabel in the TextBoxes Pin
Member 93911892-Dec-12 16:06
memberMember 93911892-Dec-12 16:06 
GeneralCorrections Pin
BrightSoul12-Dec-10 5:46
memberBrightSoul12-Dec-10 5:46 
GeneralMy vote of 5 Pin
pravin4work27-Sep-10 0:55
memberpravin4work27-Sep-10 0:55 
GeneralMy vote of 5 Pin
bigbulldawg14-Aug-10 16:31
memberbigbulldawg14-Aug-10 16:31 
Generalgives me this kindof error... Pin
zazabzulla31-Aug-09 3:58
memberzazabzulla31-Aug-09 3:58 
Generalokey how about this Pin
Arash Javadi27-May-09 4:20
memberArash Javadi27-May-09 4:20 
GeneralGenerate conditional dynamic controls and save view state Pin
Member 323276614-Feb-09 23:26
memberMember 323276614-Feb-09 23:26 
Questionhow can i get checkbox values in gridview that i inserted them dynamically? Pin
Mojtaba Madadyar14-Jun-08 11:09
memberMojtaba Madadyar14-Jun-08 11:09 
GeneralControl values are lost after post back !!! Pin
adhamzzz1-Jul-06 23:06
memberadhamzzz1-Jul-06 23:06 
QuestionCan't get value after postback Pin
Gundamrx7819-May-06 5:54
memberGundamrx7819-May-06 5:54 
AnswerRe: Can't get value after postback Pin
saswata.purkayastha@gmail.com28-Dec-06 21:05
membersaswata.purkayastha@gmail.com28-Dec-06 21:05 
Everytime you click the image button,a postback occurs.This implies that,the page is going to be loaded once again.
Since,you are creating checkbox on every page load,the checkboxes you checked dies on occurrence of postback event ie.on being posted to server and you end up seeing new checkboxes each time WHICH WERE NEVER CHECKED ANYWAY.
So,you need VIEWSTATE to persist the values among postbacks.


*Execute the code you have written in the page_load only once ie.during the first time the page is requested.

*Before you click the image button,save the state of the page in viewstate so that it can be retrieved during subsequent page loads.

Saswata Purkayastha
Satyam Computer Services.

GeneralRe: Can't get value after postback Pin
DiskJunky2-Aug-07 0:43
memberDiskJunky2-Aug-07 0:43 
GeneralRe: Can't get value after postback Pin
jugomkd18-Apr-08 0:50
memberjugomkd18-Apr-08 0:50 
Questionhow to use find control in table??? Pin
embeded25-Dec-05 16:19
memberembeded25-Dec-05 16:19 
GeneralAcess Data for update, insert, ... Pin
Vitor Hugo Barros19-Jul-05 11:59
memberVitor Hugo Barros19-Jul-05 11:59 
GeneralRe: Acess Data for update, insert, ... Pin
smair30-Aug-05 23:16
membersmair30-Aug-05 23:16 
GeneralRe: Acess Data for update, insert, ... Pin
Vitor Hugo Barros31-Aug-05 5:39
memberVitor Hugo Barros31-Aug-05 5:39 
GeneralRe: Acess Data for update, insert, ... Pin
RB@Emphasys7-Sep-06 11:23
memberRB@Emphasys7-Sep-06 11:23 
Generalfind control of placeholder,pls help:-) Pin
Anonymous19-Jul-05 9:38
sussAnonymous19-Jul-05 9:38 
GeneralLabel problem Pin
biktor817-Jun-05 7:15
memberbiktor817-Jun-05 7:15 
GeneralRe: Label problem Pin
MarcTH26-Jul-05 0:41
sussMarcTH26-Jul-05 0:41 
GeneralRe: Label problem Pin
smair30-Aug-05 23:20
membersmair30-Aug-05 23:20 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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