Dynamically adding User Control instances on Button click event

Hi All:

 I have a user control which has three text boxes in it. Now I have a page where there is a place holder and a button. On the click event of the button I add an instance of the user control to the place holder. It works fine the first time and the user control is added to the place holder. However when I click again, a new user control instance is added and the first instance is not there... same thing is repeated if I click again...new instance is added and none of the previous ones are ther ein the place holder.
The code for the web page is as follows:

int iTextBoxUserControlCount = 0;protected void Page_Load(object sender, EventArgs e)


object TextBoxUserControlCount = Session["TextBoxUserControlCount"];

if (TextBoxUserControlCount != null)


iTextBoxUserControlCount =



iTextBoxUserControlCount = 1;




protected void btnAddTextBoxes_Click(object sender, EventArgs e)





ThreeTexBoxes threeTexBoxes = (ThreeTexBoxes)this.LoadControl("ThreeTexBoxes.ascx");

threeTexBoxes.ID = "ThreeTexBoxes" + iTextBoxUserControlCount;

this.form1.Controls.Add(threeTexBoxes);Session["TextBoxUserControlCount"] = iTextBoxUserControlCount + 1;


catch (Exception ex)


this.lblError.Text = ex.Message;



Do i need to save the user control in the SaveViewState event or any other event... plz provide some example....

 Thanks for eveything


3/5/2008 7:44:16 PM
asp.net.state-management 8807 articles. 0 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 46
Get it on Google Play
Get it on Apple App Store

The problem is that you can´t to add controls to a Controls property at runtime, cause the native ViewState don´t save collections.

To do that you must to use a Repeater control and to fill it with a DataTable (or any collection). The Repeater will to repeat all the elements to any records of collection. However, the DataTable (or collection) must to persist in ViewState or Session. I would use a ViewState in your case:

private StringCollection RepeaterDataSource
        return (StringCollection)ViewState["RepeaterDataSource"];
        ViewState["RepeaterDataSource"] = value;

Excuse me for my way of writing. I don´t speak English so much.

3/5/2008 8:30:21 PM

Hi All:

 I found the solution .. I had to add the user controls to the Control hierarchy in OnInit method of the page, since I am adding them dynamically.



3/6/2008 12:10:22 AM

Similar Artilces:

Dynamically add controls to user control based on Parent page button click event
Hi, I have a page which contains a button, a dropdownlist and a user control.  The user control is added to the parent page during page_load.    If the user clicks on the button, the value in the dropdownlist is passed to the usercontrol via the usercontrols public properties and is stored in its viewstate. The user control is dynamically populated with fields based on a database id passed to it from the parent page.  I gave the user control a public property which hooked into the ViewState bag of the user control so that I could pass it the database id at r...

Dynamically loaded user control with a button doesn't fire its button click event?
I have a datagrid, in which one of the columns is 'button' column called 'Send Email'. When I click on this button, then an email user control is dynamically loaded into a placeholder above the datagrid header area. The email control renders correctly, but when I click on 'Send' button in this user control, then the click event of this 'Send' button doesn't fire. This is even though the 'Handles.btnSend.Click' is there for the click method of the 'Send' button. Can someone please tell me why the event is not firing and what do I need to do to make it fire?    sun21170 you have...

Dynamically added user controls.. Restoring user control events ...
Hello, i ve made a simple aspx page to focus on the problem..In the aspx page i have a button that when it is pressed a user control is added dynamically, So if you press the button twice , two user controls will be added..Here is how i implement it :When a user control is added ,i add it to an arraylist (which contains all the  user controls that have been inserted to the page ) and this array list is then added to the session.So when the page is loaded ,i retrieve that arraylist back from the session i iterate through it ,and i enter again to the page all the previous added user contr...

Dynamically loaded Web User Control .ascx button click event handler not called on second time click
I have an ascx control (that performs actions for an entity) being added dynamically to accordion panes, and then the panes are added to an ajax accordion control, so that the accordion can contain multiple panes with each pane containing one ascx control. The ascx control contains a delete button which removes the entity from the database. Once the entity is removed, I need to reflect this deletion in the parent page by removing the accordion pane from the accordion. To do this I created a delegate function and which is called from the parent page to rebind the accordion and hence not d...

Error when Loading Dynamic UserControl from current User Control's Button Click event Calling Page Event
Hi,I have a panel that I load user Control in no problem.  The problemarrises when I do a post back on one of these user controls.  I havebutton it does a click event.  In this click event I will do somedatabase updates, then I will use reflection to call a method in theparent (this.page) to load the new user control.  Its at this pointafter it loads the new user control that it throws the error "Thecontrol must be placed inside a form tag with runat=server".Now, my methods that managers the user control works.  I am able toclick on the parent page menu and...

Dynamically loading user control to a gridview
Hello,I know there are many posts about loading user control dynamically and events which not fire. I tried  everything suggested but nothing helped. The difference in my example is that I am loading the user control into a specific line in a grid view after the user clicked on a button.So, the containing object in this case is DataControlFieldCell but it is a difference one on every click of the user.I tried to to set the ID of the user control on the page load of the control (this.ID = "MyControl1";) and I am loading the control on post back in the page_load of the parent pa...

Button in dynamic user control need to be clicked twice to fire event?
I have created a website that uses dynamic user controls. I placed a button in a dynamic user control but its need to be clicked twice to fire event. First click doesn't work, but subsequent clicks work. What should I do? Here is my code snippets:  default.aspx---------------------------------------------------------------------- <asp:Panel ID="Panel1" runat="server"></asp:Panel> <asp:Button ID="btnAnaSayfa" runat="server" Text="AnaSayfa" onclick="btnAnaSayfa_Click" ...

Button click event not fired for a custom webpart where controls are added dynamically.
We are migrating a Sharepoint 2003 site to MOSS 2007 and ASP.NET 2.0. We have also migrated the webparts but they are still inheriting from Sharepoint.WebPart. We have a webpart where controls are added dynamically at runtime. On this webpart a button is added dynamically and a click event handler is also attached. The button on the webpart is displayed only when there is some data. The button deletes the selected row of data when clicked. But when we click on the button, the page gets posted but the event handler is not called. We analysed and found that the code where we add the button to ...

User Control Button Click Event Does Not Fire With Postback, when Loaded Dynamically
My application consists of a web form (MainForm.aspx) with a PlaceHolder (phMain) with several user controls that are loaded and removed dynamically based on the context. Two of these controls are LoginUC.aspx and DataEntryUC.ascx. Each of these controls have a 'Submit' button.When the application is launched, LoginUC is loaded to the PlaceHolder. Users enter an Id and Password, then upon authentication an event named  LoginCompleted.is raised in LoginUC. This event (LoginCompleted) is consumed in the parent form (MainForm.aspx) wherein the LoginUC control is removed...

Why is my ATLAS TEMPLATED USER CONTROL getting all instances of this controls methods called? I only want it called for the instance that I click the button from...
I have created a templated user control and it uses ATLAS. So...once the control loads, it then makes an ajax call to populate itself. "server" UpdateMode="Conditional" ID="UpdatePanel1" ChildrenAsTriggers="False" > "TNews1" runat="server"> BNNews(<%# Container.Row["TotalItems"].ToString()%>) <%# Container.Row["NewsID"] %> - "BNP35.aspx?newsId=<%# Container.Row["NewsID"]%>&promoId=<%# TN...

Button click event not getting fired for a custom webpart where controls are added dynamically.
 We are migrating from ASP.NET1.1/Sharepoint 2003 to ASP.NET 2.0/Moss 2007. We have a webpart on which controls are getting added dynamically. We have a button which is also dynamically added and a click event handler is also attached to it. However when we click on this button the page gets posted but the event is not fired. We analysed and found that the code to add the button in the webparts controls collection is executed but the code to add the button to it's container (that is a table) is not getting executed. Hence the event is not getting handled. If we forcefully add the bu...

Button Event Inside User Control Not Firing when Dynamically Created and added to Page.
Hello, I am dynamically Loading multiple instances of a UserControl and adding them to the Page.Controls collection. When I run the page the dynamically created Usercontrols are displayed with the proper data. However, when I click a LinkButton I have included in the UserControl to hide certain elements within the User Control the Page Posts back but the LinkButton.Click event does not fire inside the User Control. Further, if I just hard code the user control into the aspx file (giving me just the one instance) and I click the LinkButton the Click event does fire ins...

Button click does not fire inside a user control which is added dynamically to a ModalPopupExtender target
Hi All, I have a panel in the masterpage which has a modalpopupextender control associated to. There is a place holder inside the panel to which i dynamically add User Controls on the click of a LinkButton which resides somewhere on the page. The control gets added to the popup and the popup shows up. However when I click a button inside the User Control, its server click event does not get fired.. in turn the Master page's Page Load is fired. I forgot to mention that the link button, panel and modalpopup extender are inside a Update Panel. Following is the code snippet:&nbs...

Begginner question: adding user control via button click event after page load
Hello everybody  Beginner question... I have a page with several user controls and a button. When the user clicks the button, I'm adding an additional control to a placeholder in the click_event. However, the problem is the event handler is fired after the Page_Load event, so the additional control does not show. Being a beginner, I'm not sure what the usual way to approach this would be? Should I somehow try to fire the click event handler before the Page_Load event, or at the end of the click event should I somehow re-draw the page at that point. I know this is a basic...

Web resources about - Dynamically adding User Control instances on Button click event - asp.net.state-management

iPhone 5 A6 chip to dynamically up-clock up to 1.3GHz (and downclock too)?
Interesting video from our friends at TLDToday: If this is not just a Geekbench app glitch, it could indicate why that A6 processor is so 2X ...

Apple's Lightning port dynamically assigns pins to allow for reversible use
... a closer look at how Apple's new Lightning connector works, and has come to the conclusion that the 8 pins on each side of the plug are dynamically ...

iPhone 5 Lightning port dynamically reassigns pins
... of Apple's Lightning USB cable shows that the pins on the plug aren't arranged symmetrically, suggesting that the Lightning port can dynamically ...

Urlbox Launches Screenshots-as-a-Service Platform to Dynamically Update Galleries
... changes. Launched yesterday, Urlbox allows anyone with a gallery displaying website screenshots to automate the process and keep them dynamically ...

Everything.me launcher dynamically adapts to what you’re doing right now
... phone according to what you’re doing. Perform a search for ‘football’ and your background will change to the NFL logo. A launcher that dynamically ...

A YouTube Experiment Resizes the Player Dynamically
There's a new YouTube experiment that changes the video player's size, depending on the browser window's size. When resizing Chrome's window, ...

Apple Granted “Dynamically Changing Cursor for User Interface” Patent, Originally Filed in 2003
... a utility patent that covers the use of the mouse cursor that changes according to the context of the task it is engaged in. Called a “Dynamically ...

Atmel's FPSLIC II Dynamically Reconfigurable SoC Supports "Silicon-Sharing" For Peripherals & Interfaces ...
Silicon-Sharing Fits 200K Gate Design into 40K Gate FPSLIC II's, Cuts Power Drain by 97%

Everything.me Launcher Wants to Dynamically Change Phones Based on Location, Interests, and Mental State ...
What if your phone’s launcher dynamically changed based upon interests, your location, or topics you had in mind at a specific moment? A new ...

Resources last updated: 11/23/2015 6:56:50 PM