How to Add Controls during Runtime ( Dynamically ) in ASP.NET ?

Well i have been wandering around here and there for quite a few days in understanding how to dynamically create the controls in ASP.NET during the runtime in VS 2008.

All it ended out to be a very simple one.

How to Add Controls during Runtime ( Dynamically ) in ASP.NET ?

This is achieved through the methods Controls.add that is available with the panel or with each page.

Well this works fine with panels and few other Containers but special care has to be taken when adding to the page.Controls.I l update regarding the same in some time.

All that i have in the page is a simple Button and a Panel. When i click on the Button i need to generate a set of Controls in the Runtime.

Code Behind Page (.cs )

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
Label lb1;
TextBox txt;
Button btn1;
protected void Button1_Click(object sender, EventArgs e)
{
lb1=new Label();
txt = new TextBox();
txt.ID = "txt1";
btn1 = new Button();
btn1.ID = "bt1";
btn1.Text = "Click";
Panel1.Controls.Add(txt); Panel1.Controls.Add(btn1); Panel1.Controls.Add(lb1); 
lb1.Text = "Dynamic";
}
}

Well this seems to be easy but there are a lot of things to be explored in the same which i have been trying out and update frequently…………..

    29 Comments

  1. Muhammad Adnan
    January 29, 2009
    Reply

    I don’t know why it got considered as article of the day @ asp.net 😀 anyhow you added all the controls how about managing them as after postback by other button they will vanish and how about data in them say grid…….. its long story man and long topic to cover up.

    Anyhow good luck

  2. Kevin
    January 29, 2009
    Reply

    Just because you can do this doesn’t mean that you should. It is a VERY BAD idea to add controls at runtime like that. The more this is used to more difficult it becomes to rework the page. Develop for the person that is gonna have to debug your page, not for you right now. Avoid this at all costs!!!

  3. Thanigainathan.S
    January 29, 2009
    Reply

    Hi,

    This article is nice. Very good to learn . Will be expecting your future articles on this stuff.

    Thanks,
    Thani

  4. Naresh
    January 29, 2009
    Reply

    Very simple any way good work.

  5. Anonymous
    January 29, 2009
    Reply

    Thanks for the info. I am a beginner in ASP.NET and your article has given me inspiration that I can also write Article of the day stuff.

  6. g2k
    January 29, 2009
    Reply

    I’m not a big fan of dynamic control because of the viewstate. For instance, the control is generated when the button_click event is handled. Subsequent page load may lose those controls.

  7. Jorge
    January 29, 2009
    Reply

    I hope you can show us how to use this when a postback is triggered.

    Anyway, thanks for sharing.

  8. interpeo
    January 29, 2009
    Reply

    Hi, good article, specially for beginners.

    @Kevin, I’m quoting:
    “It is a VERY BAD idea to add controls at runtime” can you further explain what you mean by “bad idea”???

    My web apps would be very poor without the runtime “Controls.Add” magic tool!

    Thanx

  9. Raj
    January 30, 2009
    Reply

    Can anyone tell me the criteria to get article published on ASP.net …???? I can’t believe an article of this type is recognized by the no. 1 website on ASp.net.

    I can write much better article than this…!!!

  10. Rajeev
    January 30, 2009
    Reply

    Hi,

    I think it’s a Incomplete article. i appreciate senthil for writing an article and publish in asp.net website. If you add button we should need to handle it Click event at least. We need to preserve the dynamic controls if the page post back. We can’t say this an article, but a small tip for how to create asp.net controls at run time.

  11. Follower
    January 30, 2009
    Reply

    That is a bad idea?
    Why you think that is a “client” and not use the server processes unless imprescendible. For that, there is the Javascript, Ajax etc. ..
    We talk about webforms, not WinForms.
    (and the code is “simple” for newbies very good applications for Windows)

  12. Ravi Roy
    January 30, 2009
    Reply

    Creating controls at runtime you will come accross several setbacks here are some of them:

    1.> Client Side validation (Using Required field etc validator.

    2.> You will have to redraw the controls everytime even on postback.

    3.> If there are hundereds of such controls in a page you will face hell in load testing.

    I suggest it is best to have controls hidden inside a div and making them visible on demand using javascript.

    Anyone interested just mail me and I will sed the sample.

  13. khalid
    January 30, 2009
    Reply

    Very Very Very ………… what can I say?

    gooooooooooooooood luck

  14. C
    January 30, 2009
    Reply

    “Can anyone tell me the criteria to get article published on ASP.net …???? I can’t believe an article of this type is recognized by the no. 1 website on ASp.net.

    I can write much better article than this…!!!”

    This is a little bit harsh don’t you think. The author’s intent was not get recognized as the article of the day on some site. The authors intent was to share some information. At least he/she put their idea out there. Learn from it, improve it, and I’m sure the author would address constructive criticism or comments. I personally would tell you to sod off.

  15. Andy
    January 31, 2009
    Reply

    Hey Everyone,

    It is very easy to work with controls created like this. You have to realize that if you try to read the objects in during the page_load event, they will disapear. You have to read them during the PreInit() event.

    Once you do that you can manage the objects just fine.

  16. Salman Farsi
    February 1, 2009
    Reply

    Hi Everyone,

    It is good article for the beginner’s. But adding controls like this way always create some serious issues when you are going to validate this kind of controls to client side or want to work at client side. So, special care needs to add controls at runtime.

    Thanks

  17. vdx660
    February 2, 2009
    Reply

    You can put a routine to restore the controls add on the Page_Load and the controls will not disappear every time th page is loaded. I was able to make a website which had functions similar to WebParts but without the stupid aspdbnet.mdb on the App_Data folder.

  18. hassan
    February 3, 2009
    Reply

    hmm…a simple try out turns out to be article of the day @asp.net…very interesting

  19. Sandeep
    February 4, 2009
    Reply

    Good article Senthil! Don’t get frustrated with negative comments – it was a good learning experience.

  20. Russell
    February 4, 2009
    Reply

    This article might have been relevant 9 years ago when we were all learning the new framework, but hardly is it worth posting on asp.net. The vast range of knowledge in our “profession” is mind boggling. I’m sure lots of people reading asp.net are not professionals, but should those people really be posting tutorials? Also, most of the responses to this article are so wrong. The following comments are flat out wrong:

    “Just because you can do this doesn’t mean that you should. It is a VERY BAD idea to add controls at runtime like that. The more this is used to more difficult it becomes to rework the page. Develop for the person that is gonna have to debug your page, not for you right now. Avoid this at all costs!!!”

    “Very simple any way good work.”

    “Creating controls at runtime you will come accross several setbacks here are some of them:

    1.> Client Side validation (Using Required field etc validator.

    2.> You will have to redraw the controls everytime even on postback.

    3.> If there are hundereds of such controls in a page you will face hell in load testing.

    I suggest it is best to have controls hidden inside a div and making them visible on demand using javascript.

    Anyone interested just mail me and I will sed the sample.”

  21. kirthika
    February 22, 2009
    Reply

    Nice article

  22. venkat
    February 26, 2009
    Reply

    Load Control at runtime is good idea.
    load all your controls on page load hide in div tag.

  23. Jerome Dimairho
    March 11, 2009
    Reply

    That’s textbook coding 4 u. lol… It only works in the classroom. Reminds me of where I came from. Nice one!

  24. zahy
    April 13, 2009
    Reply

    that’s well, but did u try to attach events to these controls?, what happen when page is postback , i think u still have to work hardly for it.

  25. Ehsan
    May 8, 2009
    Reply

    waw ..
    so useful !
    thx man 😉

  26. Hill Hill
    July 8, 2009
    Reply

    The page’s ProcessPostData event is fired before your “Button1_Click” event. So, you won’t be able to use any server-side event of your dynamically added TextBox or Button.

    In other terms, you create a Button, but too late in the page lifecycle to be able to respond to the future click on this button.

    This is an awful code, don’t use it.

    Solutions :
    – if you can, add the controls to the form in the Page_Load, Page_InitComplete or Page_Init event.
    – if you can’t, declare a static invisible ASP.NET Panel in the page with your controls in it, and set the panel’s Visible property in the Button1_Click event.
    – if you can’t AND if you can’t know in advance how many and which controls to add dynamically, use Javascript to set and HiddenField value in the “onclick” client Function of the Button1. In the Page_Load, test the hiddenfield value to know if you clicked the button or not to add the controls as needed.

  27. Gaurav Jain
    October 8, 2009
    Reply

    Adding controls at runtime is not too difficult…
    but i want to know that how can i add event…on that run time added control…

    Please help me out ot this….
    and plzzzz reply me at

    [email protected]

  28. Nitin Goel
    May 5, 2010
    Reply

    Hi,
    I have a panel with all control and has design panel as per client requirement. at the inside panel there are one button name “add more”. when you click add more button the same panel comes after first panel with all the same control design structure.Please let me know how to add a panel with same control and how to i will read second panel control value in Data table. i can click more than time add more button, however multiple panel will show on same page with same control design.Please help me at [email protected]

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

You can read connection string from web.config file in ASP.NET by using the ConfigurationManager class in case you want to...
When you deploy your ASP.NET Web Application on Windows Server running IIS , there are times that you might receive...
This post will explain how to resolve the error “Handler “aspNetCore” has a bad module “AspNetCoreModuleV2” in its module list”...