Click here to Skip to main content
Click here to Skip to main content

Dynamically add and remove user controls

, 9 Jun 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Dynamically add and remove user controls to a page and maintain the control state.


I often find myself in a situation where I have a user input form that I want to reuse, but I don't know how many times I'll be reusing it. For example, let's say you want to let users on your site upload images, but you don't know how many images they'll want to upload. Giving the user an "Add" button can let them dynamically add as many upload boxes to the page as they want.

That's fine if you have a single control that you want to add dynamically, but what if you have several controls in a complex layout? In that case, the easiest way to handle this is by wrapping the controls you want to add into a single user control, and then dynamically adding the user control to your page. I'll show you how to do that, how to remove user controls, and also how to access the values of the controls within the user control.

Using the code

First, let's create a user control and populate it with several controls for our "template". The user control content looks like this:

            <td>Textbox Example:</td>
                <asp:TextBox ID="tbx1" runat="server" />
            <td>Dropdown Example:</td>
                <asp:DropDownList ID="ddl1" runat="server">
                    <asp:ListItem Text="Dropdown 1" />
                    <asp:ListItem Text="Dropdown 2" />
                    <asp:ListItem Text="Dropdown 3" />
            <td>Checkbox Example:</td>
                <asp:CheckBoxList ID="cbx1" runat="server">
                    <asp:ListItem Text="Checkbox 1" />
                    <asp:ListItem Text="Checkbox 2" />
                    <asp:ListItem Text="Checkbox 3" />
    <asp:Button ID="btnRemove" runat="server" Text="Remove" />
    <hr />

Now, add an event handler to the code-behind on the user control so we can tell when the Delete button was clicked:

 Partial Class WebUserControl
    Inherits System.Web.UI.UserControl

    'Declare the event that we want to raise 
    '(we'll handle this in the parent page)
    Public Event RemoveUserControl As EventHandler

    Protected Friend Sub btnRemove_Click(ByVal sender As Object, _
              ByVal e As System.EventArgs) Handles btnRemove.Click
        'Raise this event so the parent page can handle it
        RaiseEvent RemoveUserControl(sender, e)
    End Sub
End Class

Now that we have the controls we want to display, we'll add the user control to another page dynamically.

There are three important things we have to do in the page load. First, we need to determine what control fired the postback. We need to make sure the "Add" button was clicked.

This needs to be done in the page load event, instead of in the onclick event for the "Add" button, because of the way the ASP.NET page lifecycle works. If we try to add any controls in the onclick event for the Add button (instead of the page load), those values will be blown away when the page posts back.

If the "Add" button was clicked, the next thing to do is increment the count of the user controls to add to the page, so we know how many controls to display. I store this value in a Literal control across postbacks.

We also need to attach an event handler to take care of the 'Delete' button on the user control when it gets clicked. This will remove the control from the Panel and decrement the number of controls on the page.

Finally, once all the setup is taken care of, we can dynamically load all the requested user controls into a PlaceHolder control.

Protected Sub Page_Load(ByVal sender As Object, _
              ByVal e As System.EventArgs) Handles Me.Load
    End Sub

    Private Sub AddAndRemoveDynamicControls()
        'Determine which control fired the postback event. 
        Dim c As Control = GetPostBackControl(Page)

        If Not IsNothing(c) Then
            'If the add button was clicked, increase 
            'the count to let the page know we want
            'to display an additional user control
            If c.ID.ToString = "btnAdd" Then
                ltlCount.Text = Convert.ToInt16(ltlCount.Text) + 1
            End If
        End If

        'Be sure everything in the placeholder control is cleared out

        Dim ControlID As Integer = 0

        'Since these are dynamic user controls, re-add them every time the page loads.
        For i As Integer = 0 To (Convert.ToInt16(ltlCount.Text) - 1)
            Dim DynamicUserControl As WebUserControl = _

            'If this particular control id has been deleted 
            'from the page, DO NOT use it again. If we do, it will
            'pick up the viewstate data from the old item that 
            'had this control id, instead of generating
            'a completely new control. Instead, increment 
            'the control ID so we're guaranteed to get a "new"
            'control that doesn't have any lingering information in the viewstate.
            While InDeletedList("uc" & ControlID) = True
                ControlID += 1
            End While

            'Note that if the item has not been deleted from the page, 
            'we DO want it to use the same control id
            'as it used before, so it will automatically maintain 
            'the viewstate information of the user control
            'for us.
            DynamicUserControl.ID = "uc" & ControlID

            'Add an event handler to this control to raise 
            'an event when the delete button is clicked
            'on the user control
            AddHandler DynamicUserControl.RemoveUserControl, _
                       AddressOf Me.HandleRemoveUserControl

            'Finally, add the user control to the panel

            'Increment the control id for the next round through the loop
            ControlID += 1
    End Sub

    Private Function InDeletedList(ByVal ControlID As String) As Boolean
        'Determine if the passed in user control ID 
        'has been stored in the list of controls that
        'were previously deleted off the page
        Dim DeletedList() As String = ltlRemoved.Text.Split("|")
        For i As Integer = 0 To DeletedList.GetLength(0) - 1
            If ControlID.ToLower = DeletedList(i).ToLower Then
                Return True
            End If
        Return False
    End Function

    Sub HandleRemoveUserControl(ByVal sender As Object, ByVal e As EventArgs)
        'This handles delete event fired from the user control

        'Get the user control that fired this event, and remove it
        Dim DynamicUserControl As WebUserControl = sender.parent

        'Keep a pipe delimited list of which user controls 
        'were removed. This will increase the 
        'viewstate size if the user keeps removing 
        'dynamic controls, but under normal use
        'this is such a small increase in size that it shouldn't be an issue.
        ltlRemoved.Text &= DynamicUserControl.ID & "|"

        'Also, now that we've removed a user control decrement 
        'the count of total user controls on the page
        ltlCount.Text = Convert.ToInt16(ltlCount.Text) - 1
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, _
              ByVal e As System.EventArgs) Handles btnAdd.Click
        'Handled in page load
    End Sub

There's one more issue here. How do we get at the values stored in the user controls? It's actually fairly straightforward. We loop through all the controls in the PlaceHolder, then look at the name of the control to determine if this is one of the user controls we added to the PlaceHolder.

If it is, we can use FindControl to access the values stored in textboxes, dropdowns, checkboxes, or anything else we added to the user control. Here, I'm getting those values and then writing them out to the screen:

Protected Sub btnDisplayValues_Click(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles btnDisplayValues.Click
        ltlValues.Text = ""
    For Each c As Control In ph1.Controls
        'Find the specific user control that we added to this 
        'placeholder, and then get the selected values
        'for the dropdownlist, checkbox, and textbox and print them to the screen.
        If c.GetType.Name.ToLower = "webusercontrol_ascx" Then
            Dim uc As UserControl = CType(c, UserControl)
            Dim tbx1 As TextBox = uc.FindControl("tbx1")
            Dim ddl1 As DropDownList = uc.FindControl("ddl1")
            Dim cbx1 As CheckBoxList = uc.FindControl("cbx1")

            Dim sb As New System.Text.StringBuilder
            sb.Append("Textbox value: " & tbx1.Text & "<br />")
            sb.Append("Dropdown value: " & ddl1.SelectedValue & "<br />")
            sb.AppendLine("Checkbox values: ")

            For Each li As ListItem In cbx1.Items
                If li.Selected = True Then
                    sb.Append(li.Value & "<br />")
                End If

            sb.Append("<hr />")

            ltlValues.Text &= sb.ToString
        End If
End Sub

I hope this has given you another way to think about dynamically adding and removing controls. Enjoy!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Neil Meredith
Software Developer (Senior)
United States United States
I am a .Net developer with 8 years of professional development experience. After 4 years in Florida, I made my way up to the frozen north and am currently living in Chicago.
For more development tips and tricks (focusing on game development with Unity), check out my blog at
Google Plus Profile
Follow on   Twitter

Comments and Discussions

QuestionError 150 'RemoveUserControl' is not an event of 'System.Web.UI.UserControl'. \Pages\Application.aspx.vb 35 43 XXXXXXXXXXXX PinprofessionalManikandan MAC6-Mar-14 5:05 
QuestionDynamically add and remove user controls with layout PinmemberSocrate117-Oct-13 10:21 
GeneralMy vote of 5 Pinmemberlilbucky7211-Mar-13 19:46 
QuestionExcellent but still needs help PinmemberMember 128334730-Sep-12 17:38 
QuestionHow can I add fixed number of controls Pinmembervmaxp2-May-12 4:28 
AnswerRe: How can I add fixed number of controls PinmemberNeil Meredith2-May-12 5:56 
QuestionDynamic user controls inside dynamic user controls... PinmemberMember 871483626-Mar-12 9:20 
GeneralMy vote of 5 PinmemberMember 871483626-Mar-12 9:02 
QuestionAdd Radio Button PinmemberjWiki18-Mar-12 8:28 
GeneralMy vote of 5 PinmemberMarcio_Coelho19-Dec-11 9:43 
GeneralMy vote of 4 PinmemberRamonCruz11-Dec-11 23:42 
Questioncould u help me about this PinmemberMurali.P16-Aug-11 21:31 
AnswerRe: could u help me about this Pinmemberppaustralia14-Feb-14 17:20 
Generalplease can someone help me and tell me how to get this by C# PinmemberMember 79046289-May-11 6:57 
GeneralRe: please can someone help me and tell me how to get this by C# PinmemberTing Qin26-May-11 5:19 
GeneralFantastic Article! Pinmembertriple G30-Apr-11 12:04 
QuestionCan I get the Article in C# Pinmemberbrijniks22-Mar-11 18:10 
AnswerRe: Can I get the Article in C# PinmemberMember 79046289-May-11 6:57 
AnswerRe: Can I get the Article in C# Pinmvpthatraja26-Jan-12 22:14 
AnswerRe: Can I get the Article in C# PinmemberMember 790462813-May-11 13:12 
AnswerRe: Can I get the Article in C# Pinmvpthatraja26-Jan-12 22:14 
QuestionPassing Values from Parent Page to user Control and maintaining the values added PinmemberChetan A. Sharma18-Mar-11 5:44 
Hi - This is a very good article. I wanted to know if we can pass values from Parent page (in this case from Default.aspx page) to the user control and maintain those values on subsequent "Add/Load" of user control.
So in short, if I click the "Add" button it loads my "webusercontrol" and also I am able to pass my default.aspx dropdownlist value to this dynamically loaded user control and assign it to a "Label or Textbox" which resides in my "webusercontrol", now the problem is that the value doesn't persists! What I meant is , when I click "Add" button again the "webusercontrol" gets loaded again perfectly but now all my "Label's" in webusercontrol has the new selected value from the default.aspx dropdownlist.
So say for instance I have a Dropdownlist in Default.aspx page with Values "Apple, BlackBerry, Nokia" and initial value to be passed is "Apple", I click the "Add" button, now my "Label" inside webusercontrol has the value "Apple", perfect! Next when I click "Add" button again and select a different value to be passed this time say "BlackBerry" now I have 2 webusercontrol loaded on the page, so that means I have 2 "Labels" with different ID's, but now my first Label initially had the value "Apple" because that's what I had passed and now when I passed the value "Blackberry" both the labels of my webusercontrol has the value "BlackBerry" instead of one being "Apple" and another "BlackBerry"
Is there a way to resolve this issue?
Any help would be appreciated! Thanks!
Confused | :confused:

GeneralLiterals Pinmemberjeffjcom29-Dec-10 9:25 
GeneralYou're a saint... Pinmemberjulian@giant28-Oct-10 7:22 
GeneralRe: You're a saint... PinmemberNeil Meredith28-Oct-10 13:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 9 Jun 2008
Article Copyright 2008 by Neil Meredith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid