Dynamically add and remove User Control to PlaceHolder using C# in ASP.Net

Last Reply 7 months ago By AnandM

Posted 8 months ago

I make one asp.net web forms app, I create user control, in this user control I insert few standard .net controls. Now in my page.aspx I want dynamicly to insert this user control. I put a button, something like "Add new control". If I click on it I'm adding a new control to the page. And all this works fine.

I have a problem in removing of this controls. I write a function for removing. But first time when I click it doesn't remove the control, I have to click another time to remove the last control. I think is something with postback, don't know why at first post back it doesn't remove the control.

 

I insert user control into 

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

 

This is c# code:

 

 

 

public partial class Clasess_And_Events : System.Web.UI.Page
{
    protected int NumberControlsForCategory
    {
        get { return (int)ViewState["NumControlsForCategory"]; }
        set { ViewState["NumControlsForCategory"] = value; }
    }

 

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            //Initiate the counter of dynamically added controls
            this.NumberControlsForCategory = 0;
           
        }
        else
        {
                //Controls must be repeatedly be created on postback
                this.createControlsCategory();
              
        }

 
           
    }

    private void createControlsCategory()
    {
        int count = this.NumberControlsForCategory;

        for (int i = 0; i < count; i++)
        {
             

            Control myUserControl = (Control)Page.LoadControl("UserControls/CategoryDropdown.ascx");
            myUserControl.ID = "CategoryControl_ID_" + i.ToString();

           
            PlaceHolder1.Controls.Add(myUserControl);
        }
    }
 
 

    protected void Add_Control_Click(object sender, EventArgs e)
    {


        Control myUserControl = (Control)Page.LoadControl("UserControls/CategoryDropdown.ascx");
        myUserControl.ID = "CategoryControl_ID_" + NumberControlsForCategory.ToString();

         
        PlaceHolder1.Controls.Add(myUserControl);

        this.NumberControlsForCategory++;

        LinkButton10.Visible = true;
    }

 
 



    protected void Remove_Control_Click(object sender, EventArgs e)
    {
         
                Control myUserControl = (Control)Page.FindControl("CategoryControl_ID_" + NumberControlsForCategory.ToString());
                PlaceHolder1.Controls.Remove(myUserControl);
                this.NumberControlsForCategory--;

     }
}

 

Posted 7 months ago Modified on 7 months ago

Hi yorke,

I have created a sample which full fill your requirement

UserControl

<table>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            Country:
        </td>
        <td>
            <asp:DropDownList ID="ddlCountry" runat="server">
                <asp:ListItem Text="-Select-" />
                <asp:ListItem Text="India" />
                <asp:ListItem Text="USA" />
                <asp:ListItem Text="Canada" />
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td>
            Education:
        </td>
        <td>
            <asp:CheckBoxList ID="cblEducation" runat="server">
                <asp:ListItem Text="BTech" />
                <asp:ListItem Text="MCA" />
                <asp:ListItem Text="MTech" />
            </asp:CheckBoxList>
        </td>
    </tr>
</table>
<asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
<hr />

UserControl.ascx.cs

//Declare the event that we want to raise (we'll handle this in the parent page)
public event EventHandler RemoveUserControl;

protected internal void btnRemove_Click(object sender, System.EventArgs e)
{
    //Raise this event so the parent page can handle it    
    RemoveUserControl(sender, e);
}

CS.aspx

<%@ Register Src="~/UserControl.ascx" TagName="UserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="sm1" runat="server" />
        <asp:UpdatePanel ID="up1" runat="server">
            <ContentTemplate>
                <div class="demo">
                    <asp:PlaceHolder ID="ph1" runat="server" />
                    <asp:Button ID="btnAdd" runat="server" Text="Add" />
                </div>
                <div class="demo">
                    <asp:Literal ID="ltlValues" runat="server" />
                    <asp:Button ID="btnDisplayValues" runat="server" Text="Display Values" OnClick="btnDisplayValues_Click" />
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:Literal ID="ltlCount" runat="server" Text="0" Visible="false" />
        <asp:Literal ID="ltlRemoved" runat="server" Visible="false" />
    </div>
    <style type="text/css">
        div.demo
        {
            width: 300px;
            float: left;
            padding: 20px;
            margin: 10px;
            border: solid green 1px;
        }
    </style>
    </form>
</body>
</html>

CS.aspx.cs

protected void Page_Load(object sender, System.EventArgs e)
{
    AddAndRemoveDynamicControls();
}

private void AddAndRemoveDynamicControls()
{    
    Control c = GetPostBackControl(Page);

    if ((c != null))
    {        
        if (c.ID.ToString() == "btnAdd")
        {
            ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
        }
    }
    
    ph1.Controls.Clear();
    int ControlID = 0;    
    for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
    {
        UserControl DynamicUserControl = (UserControl)LoadControl("UserControl.ascx");
                   
        while (InDeletedList("uc" + ControlID) == true)
        {
            ControlID += 1;
        }
        
        DynamicUserControl.ID = "uc" + ControlID;        
        DynamicUserControl.RemoveUserControl += this.HandleRemoveUserControl;
        ph1.Controls.Add(DynamicUserControl);        
        ControlID += 1;
    }
}

private bool InDeletedList(string ControlID)
{    
    string[] DeletedList = ltlRemoved.Text.Split('|');
    for (int i = 0; i <= DeletedList.GetLength(0) - 1; i++)
    {
        if (ControlID.ToLower() == DeletedList[i].ToLower())
        {
            return true;
        }
    }
    return false;
}

public void HandleRemoveUserControl(object sender, EventArgs e)
{    
    Button remove = (sender as Button);    
    UserControl DynamicUserControl = (UserControl)remove.Parent;
    ph1.Controls.Remove((UserControl)remove.Parent);    
    ltlRemoved.Text += DynamicUserControl.ID + "|";    
    ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
}

protected void btnAdd_Click(object sender, System.EventArgs e)
{
    //Handled in page load
}

protected void btnDisplayValues_Click(object sender, System.EventArgs e)
{
    ltlValues.Text = "";
    foreach (Control c in ph1.Controls)
    {        
        if (c.GetType().Name.ToLower() == "usercontrol_ascx")
        {
            UserControl uc = (UserControl)c;
            TextBox tbx1 = uc.FindControl("txtName") as TextBox;
            DropDownList ddl1 = uc.FindControl("ddlCountry") as DropDownList;
            CheckBoxList cbx1 = uc.FindControl("cblEducation") as CheckBoxList;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("Name: " + tbx1.Text + "<br />");
            sb.Append("Country: " + ddl1.SelectedValue + "<br />");
            sb.AppendLine("Education: ");
            foreach (ListItem li in cbx1.Items)
            {
                if (li.Selected == true)
                {
                    sb.Append(li.Value + "<br />");
                }
            }
            sb.Append("<hr />");
            ltlValues.Text += sb.ToString();
        }
    }
}

//Find the control that caused the postback.
public Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if ((ctrlname != null) & ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

ScreenShot

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html?aff_id=108