Click here to Skip to main content
6,290,721 members and growing! (15,908 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate License: The Code Project Open License (CPOL)

Dynamically Created Controls in ASP.NET

By Leon Langleyben

How to dynamically create controls in an ASP.NET page.
C#, Windows, .NET 1.0, .NET 1.1, ASP.NET, VS.NET2003, Dev
Posted:27 Aug 2004
Views:119,498
Bookmarked:49 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
31 votes for this article.
Popularity: 4.63 Rating: 3.10 out of 5
7 votes, 22.6%
1
2 votes, 6.5%
2
1 vote, 3.2%
3
6 votes, 19.4%
4
15 votes, 48.4%
5

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)

About the Author

Leon Langleyben


Member
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
Occupation: Web Developer
Location: Israel Israel

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
AnswerExcellent! Pinmemberhungvm0:34 26 Mar '09  
Questionhow to add events to dynamically created and binding links PinmemberMember 40714404:32 3 Mar '09  
GeneralHow do you find the path to the control later? Pinmembermicha.gluskin5:49 25 Nov '08  
GeneralAfter the Post back, control is disappeared. Pinmemberantonyvijayan2:38 3 Jun '08  
GeneralRe: After the Post back, control is disappeared. Pinmemberantonyvijayan0:25 15 Jul '08  
QuestionProb with dynamic menulist event at runtime PinmemberHarry Sun4:34 7 May '08  
QuestionImageButton help Pinmemberjdanastasi23:15 5 Apr '08  
GeneralBig Thankx Pinmemberjoeizzy17:43 24 Jun '07  
QuestionAdding controls in flow layout Pinmembermitdej21:56 10 May '07  
GeneralHow do I add radio Buttons in a table row and control them programatically Pinmembercyprosoft8:28 23 Feb '07  
Generalprob with fire eventhandeler for Dynamically Created Controls in ASP.NET Pinmemberchiluka satish13:14 16 Feb '07  
GeneralTHANK YOU THANK YOU THANK YOU THANK YOU THANK YOU Pinmemberbmatz7:38 18 Oct '06  
Generalhow to add new controls and fire its event at runtime Pinmemberdearvivek21:32 25 Sep '06  
GeneralWorks for LinkButton but not ImageButton PinmemberAndy R Hore5:39 27 Feb '06  
GeneralRe: Works for LinkButton but not ImageButton Pinmembermbsum22:09 3 Sep '06  
Generaldynamic controls and the control tree PinsussAnonymous15:37 17 Jul '05  
GeneralDynamically adding a user control based on an event from another control Pinmembersempko20:46 13 Jul '05  
GeneralRe: Dynamically adding a user control based on an event from another control PinsussAnonymous15:00 28 Aug '05  
GeneralPage Load Occurs first on Button Click Event PinsussAnonymous21:08 11 May '05  
GeneralRe: Page Load Occurs first on Button Click Event Pinmemberhetauda8:00 18 Aug '06  
Generalabout calendar in asp.net Pinmembernirav9921:02 15 Feb '05  
Generalabout calendar in asp.net Pinmembernirav9921:00 15 Feb '05  
Generalabout calendar in asp.net Pinmembernirav9920:59 15 Feb '05  
Generalabout calendar in asp.net Pinmembernirav9920:57 15 Feb '05  
GeneralA similar approach PinmemberA_Big_Newfoundland15:47 31 Aug '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Aug 2004
Editor: Chris Maunder
Copyright 2004 by Leon Langleyben
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project