Click here to Skip to main content
12,897,457 members (51,305 online)
Click here to Skip to main content
Add your own
alternative version

Stats

262.6K views
7K downloads
60 bookmarked
Posted 27 Aug 2004

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

You may also be interested in...

Pro

Comments and Discussions

 
QuestionHow do you find the path to the control later? Pin
micha.gluskin25-Nov-08 4:49
membermicha.gluskin25-Nov-08 4:49 
GeneralAfter the Post back, control is disappeared. Pin
antonyvijayan3-Jun-08 1:38
memberantonyvijayan3-Jun-08 1:38 
GeneralRe: After the Post back, control is disappeared. Pin
antonyvijayan14-Jul-08 23:25
memberantonyvijayan14-Jul-08 23:25 
QuestionProb with dynamic menulist event at runtime Pin
Harry Sun7-May-08 3:34
memberHarry Sun7-May-08 3:34 
I am creating a SubMenuList at runtime which generated at runtime according to MainMenulist in a web form. Everything works fine at the first page load. When switch MainMenulist (by click different menuitem in MainMenulist), the SubMenuList MenuItemClick can not be handled at the first time click on the SubMenuList Item. Click again, everything is fine. This problem occurs each time switch MainMenuList. Can anyone help me out. Many tanks in advance.

Here is my code:

protected override void OnLoad(EventArgs e)
{...
this.placeHolderMain.Controls.Add(GetMenu());//Create MainMenuList
if (Session["MenuE"] != null)
{
string menue = Session["MenuE"].ToString(); //Session["MenuE"] is to record MainMenuList Item Value
PopulateSubMenu(menue); //Create SubMenuList according to param "menue"
}
...}

private void mainMenu_MenuItemClick(object sender, MenuEventArgs e)
{
string menue = e.Item.Value;
PopulateSubMenu(menue);
}

protected void PopulateSubMenu(string menue)
{
...
submenu.MenuItemClick+=new MenuEventHandler(submenu_MenuItemClick);
QuestionImageButton help Pin
jdanastasi5-Apr-08 22:15
memberjdanastasi5-Apr-08 22:15 
GeneralBig Thankx Pin
joeizzy24-Jun-07 16:43
memberjoeizzy24-Jun-07 16:43 
QuestionAdding controls in flow layout Pin
mitdej10-May-07 20:56
membermitdej10-May-07 20:56 
QuestionHow do I add radio Buttons in a table row and control them programatically Pin
cyprosoft23-Feb-07 7:28
membercyprosoft23-Feb-07 7:28 
Generalprob with fire eventhandeler for Dynamically Created Controls in ASP.NET Pin
chiluka satish16-Feb-07 12:14
memberchiluka satish16-Feb-07 12:14 
GeneralTHANK YOU THANK YOU THANK YOU THANK YOU THANK YOU Pin
bmatz18-Oct-06 6:38
memberbmatz18-Oct-06 6:38 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170424.1 | Last Updated 28 Aug 2004
Article Copyright 2004 by Leon Langleyben
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid