Click here to Skip to main content
11,413,961 members (68,487 online)
Click here to Skip to main content

Dynamically Created Controls in ASP.NET

, 27 Aug 2004 CPOL
Rate this:
Please Sign up or sign in to vote.
How to dynamically create controls in an ASP.NET page.

Introduction

Adding controls to an ASP.NET WebForm at runtime is a simple task:

private void Page_Load(object sender, System.EventArgs e)
{
    Button newButton = new Button();
    newButton.Text = "New Button"; 
    newButton.ID = "newButton"; 
    newButton.Click += new System.EventHandler(this.newButton_Click); 

    WebUserControl1 newUserControl = 
           (WebUserControl1)LoadControl("WebUserControl1.ascx"); 
    newUserControl.ID = "newUserControl";
    this.PlaceHolder.Add(newUserControl); 
    this.PlaceHolder.Add(newButton);
}

Problem

Now, let's raise a bit little. What if we want to add a new control as a result of some user action (button click, for example)? We are moving the same code from Page_Load to Button_Click event and… here troubles begin. Our controls will show as expected, but only the first time. Any postback will reset the page to its original state. Dynamically created controls will be unable to fire any event. What is happening here? The answer is simple. Page class is stateless. It is destroyed after rendering. Page recreates child controls collection, based on tags in aspx file, then postback data can be handled and event handlers attached (in OnInit event). Controls we just created dynamically do not exist in aspx file; Page has no knowledge about them.

Solution

The solution is also simple. We have to recreate controls on load stage of page lifecycle. After it's done, each control can handle its postback data, retrieve saved viewstate, raise events etc.

Now, the code skeleton will look like this:

private void Page_Load(object sender, System.EventArgs e)
{
    RecreatePersistedControls();
}
private void Button_Click(object sender, System.EventArgs e)
{
    CreateControl("newControl");
    PersistControl("newControl");
}
private void RecreatePersistedControls()
{
    // Call CreateControl for each persisted control
}
private void CreateControl(string id)
{
    // Create controll with specified id, 
    // add it to controls collection, attach event handlers
}
private void PersistControl(string id)
{
    // Persist specified id (in session for example)
}

Download source files to see the fully functional sample.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Leon Langleyben
Web Developer
Israel Israel
Leon works as Chief Architect at SRL Group. He leads architectural design and development of various enterprise level projects.
You can meet him on user groups, conferences and forums dedicated to Architecture, ASP.NET, Team System etc. or join him for the next white water rafting adventure

Comments and Discussions

 
QuestionValidating and save Dynamically created server side controls data into database Pin
ankushbelorkar, 15-Feb-13 22:02
memberankushbelorkar15-Feb-13 22:02 
QuestionAnother link Pin
sandip_frm_NEPAL, 22-Jun-12 5:52
membersandip_frm_NEPAL22-Jun-12 5:52 
Questiontotally dynamic controls Pin
mathewtinu, 25-Apr-12 10:59
membermathewtinu25-Apr-12 10:59 
Questionusing vb? Pin
JavaCookies, 19-Jan-12 20:24
memberJavaCookies19-Jan-12 20:24 
AnswerRe: using vb? Pin
Member 8152021, 11-Dec-14 22:42
memberMember 815202111-Dec-14 22:42 
AnswerExcellent! Pin
hungvm, 26-Mar-09 0:34
memberhungvm26-Mar-09 0:34 
The code in this article is a little old-fashioned (VS 2003) but it works like a charm! Thank you. Laugh | :laugh:
Questionhow to add events to dynamically created and binding links Pin
Member 4071440, 3-Mar-09 4:32
memberMember 40714403-Mar-09 4:32 
AnswerRe: how to add events to dynamically created and binding links Pin
amit_jain_online, 15-Apr-12 23:15
memberamit_jain_online15-Apr-12 23:15 
QuestionHow do you find the path to the control later? Pin
micha.gluskin, 25-Nov-08 5:49
membermicha.gluskin25-Nov-08 5:49 
GeneralAfter the Post back, control is disappeared. Pin
antonyvijayan, 3-Jun-08 2:38
memberantonyvijayan3-Jun-08 2:38 
GeneralRe: After the Post back, control is disappeared. Pin
antonyvijayan, 15-Jul-08 0:25
memberantonyvijayan15-Jul-08 0:25 
QuestionProb with dynamic menulist event at runtime Pin
Harry Sun, 7-May-08 4:34
memberHarry Sun7-May-08 4:34 
QuestionImageButton help Pin
jdanastasi, 5-Apr-08 23:15
memberjdanastasi5-Apr-08 23:15 
GeneralBig Thankx Pin
joeizzy, 24-Jun-07 17:43
memberjoeizzy24-Jun-07 17:43 
QuestionAdding controls in flow layout Pin
mitdej, 10-May-07 21:56
membermitdej10-May-07 21:56 
QuestionHow do I add radio Buttons in a table row and control them programatically Pin
cyprosoft, 23-Feb-07 8:28
membercyprosoft23-Feb-07 8:28 
Generalprob with fire eventhandeler for Dynamically Created Controls in ASP.NET Pin
chiluka satish, 16-Feb-07 13:14
memberchiluka satish16-Feb-07 13:14 
GeneralTHANK YOU THANK YOU THANK YOU THANK YOU THANK YOU Pin
bmatz, 18-Oct-06 7:38
memberbmatz18-Oct-06 7:38 
Questionhow to add new controls and fire its event at runtime Pin
dearvivek, 25-Sep-06 21:32
memberdearvivek25-Sep-06 21:32 
GeneralWorks for LinkButton but not ImageButton Pin
Andy R Hore, 27-Feb-06 5:39
memberAndy R Hore27-Feb-06 5:39 
GeneralRe: Works for LinkButton but not ImageButton Pin
mbsum, 3-Sep-06 22:09
membermbsum3-Sep-06 22:09 
Generaldynamic controls and the control tree Pin
Anonymous, 17-Jul-05 15:37
sussAnonymous17-Jul-05 15:37 
GeneralDynamically adding a user control based on an event from another control Pin
sempko, 13-Jul-05 20:46
membersempko13-Jul-05 20:46 
GeneralRe: Dynamically adding a user control based on an event from another control Pin
Anonymous, 28-Aug-05 15:00
sussAnonymous28-Aug-05 15:00 
GeneralPage Load Occurs first on Button Click Event Pin
Anonymous, 11-May-05 21:08
sussAnonymous11-May-05 21:08 
GeneralRe: Page Load Occurs first on Button Click Event Pin
hetauda, 18-Aug-06 8:00
memberhetauda18-Aug-06 8:00 
Generalabout calendar in asp.net Pin
nirav99, 15-Feb-05 21:02
membernirav9915-Feb-05 21:02 
Generalabout calendar in asp.net Pin
nirav99, 15-Feb-05 21:00
membernirav9915-Feb-05 21:00 
Generalabout calendar in asp.net Pin
nirav99, 15-Feb-05 20:59
membernirav9915-Feb-05 20:59 
Generalabout calendar in asp.net Pin
nirav99, 15-Feb-05 20:57
membernirav9915-Feb-05 20:57 
GeneralA similar approach Pin
A_Big_Newfoundland, 31-Aug-04 15:47
memberA_Big_Newfoundland31-Aug-04 15:47 
GeneralRe: A similar approach Pin
Leon Langleyben, 31-Aug-04 21:15
memberLeon Langleyben31-Aug-04 21:15 
GeneralDyanamically Created Controls Pin
PraveenTVS, 30-Aug-04 0:13
memberPraveenTVS30-Aug-04 0:13 
GeneralRe: Dyanamically Created Controls Pin
Leon Langleyben, 30-Aug-04 22:39
memberLeon Langleyben30-Aug-04 22:39 
Questionwhat about content of dynamic controls Pin
Rex_canedo, 28-Aug-04 15:32
memberRex_canedo28-Aug-04 15:32 
AnswerRe: what about content of dynamic controls Pin
Anonymous, 29-Aug-04 0:13
sussAnonymous29-Aug-04 0:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web04 | 2.8.150427.2 | Last Updated 28 Aug 2004
Article Copyright 2004 by Leon Langleyben
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid