Click here to Skip to main content
15,868,051 members
Articles / Web Development / ASP.NET
Article

Dynamically Created Controls in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.23/5 (35 votes)
27 Aug 2004CPOL1 min read 311.4K   7.3K   60   36
How to dynamically create controls in an ASP.NET page.

Introduction

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

C#
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:

C#
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)


Written By
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

 
GeneralRe: After the Post back, control is disappeared. Pin
antonyvijayan14-Jul-08 23:25
antonyvijayan14-Jul-08 23:25 
QuestionProb with dynamic menulist event at runtime Pin
Harry Sun7-May-08 3:34
Harry Sun7-May-08 3:34 
QuestionImageButton help Pin
jdanastasi5-Apr-08 22:15
jdanastasi5-Apr-08 22:15 
GeneralBig Thankx Pin
joeizzy24-Jun-07 16:43
joeizzy24-Jun-07 16:43 
QuestionAdding controls in flow layout Pin
mitdej10-May-07 20:56
mitdej10-May-07 20:56 
QuestionHow do I add radio Buttons in a table row and control them programatically Pin
cyprosoft23-Feb-07 7:28
cyprosoft23-Feb-07 7:28 
Generalprob with fire eventhandeler for Dynamically Created Controls in ASP.NET Pin
chiluka satish16-Feb-07 12:14
chiluka satish16-Feb-07 12:14 
GeneralTHANK YOU THANK YOU THANK YOU THANK YOU THANK YOU Pin
bmatz18-Oct-06 6:38
bmatz18-Oct-06 6:38 
Questionhow to add new controls and fire its event at runtime Pin
dearvivek25-Sep-06 20:32
dearvivek25-Sep-06 20:32 
GeneralWorks for LinkButton but not ImageButton Pin
Andrew Hore27-Feb-06 4:39
Andrew Hore27-Feb-06 4:39 
GeneralRe: Works for LinkButton but not ImageButton Pin
mbbisht3-Sep-06 21:09
mbbisht3-Sep-06 21:09 
Generaldynamic controls and the control tree Pin
Anonymous17-Jul-05 14:37
Anonymous17-Jul-05 14:37 
GeneralDynamically adding a user control based on an event from another control Pin
sempko13-Jul-05 19:46
sempko13-Jul-05 19:46 
GeneralRe: Dynamically adding a user control based on an event from another control Pin
Anonymous28-Aug-05 14:00
Anonymous28-Aug-05 14:00 
GeneralPage Load Occurs first on Button Click Event Pin
Anonymous11-May-05 20:08
Anonymous11-May-05 20:08 
GeneralRe: Page Load Occurs first on Button Click Event Pin
hetauda18-Aug-06 7:00
hetauda18-Aug-06 7:00 
Generalabout calendar in asp.net Pin
nirav9915-Feb-05 20:02
nirav9915-Feb-05 20:02 
Generalabout calendar in asp.net Pin
nirav9915-Feb-05 20:00
nirav9915-Feb-05 20:00 
Generalabout calendar in asp.net Pin
nirav9915-Feb-05 19:59
nirav9915-Feb-05 19:59 
Generalabout calendar in asp.net Pin
nirav9915-Feb-05 19:57
nirav9915-Feb-05 19:57 
GeneralA similar approach Pin
DanMayer31-Aug-04 14:47
DanMayer31-Aug-04 14:47 
GeneralRe: A similar approach Pin
Leon Langleyben31-Aug-04 20:15
Leon Langleyben31-Aug-04 20:15 
GeneralDyanamically Created Controls Pin
PraveenTVS29-Aug-04 23:13
PraveenTVS29-Aug-04 23:13 
GeneralRe: Dyanamically Created Controls Pin
Leon Langleyben30-Aug-04 21:39
Leon Langleyben30-Aug-04 21:39 
Questionwhat about content of dynamic controls Pin
Member 34117128-Aug-04 14:32
Member 34117128-Aug-04 14:32 

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.