如何删除.net中动态添加的控件?

时间:2013-10-01 11:07:54

标签: c# asp.net user-controls

我想删除动态添加的用户控件

我试过但是没有删除

代码:

的.ascx

<asp:Button ID="removebtn" runat="server" Text="Remove" OnClick="removebtn_Click"  />

.ascx.cs

public event EventHandler UserControlButtonClicked;

public void OnUserControlButtonClick()
{
  if (UserControlButtonClicked != null)
  {
     UserControlButtonClicked(this, EventArgs.Empty);
  }
}

protected void removebtn_Click(object sender, EventArgs e)
{
    OnUserControlButtonClick();
}

的.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="New_Employee.aspx.cs" Inherits="Portal.New_Employee" %>
 <%@ Register Src="~/VisaUserControl.ascx" TagName="VisaUserControl" TagPrefix="uc" %>

 <div id="div1" runat="server">   
 <uc:VisaUserControl ID="VisaUserControl1" Visible="false" runat="server" />
 <asp:Repeater ID="rpt1" runat="server">
 <ItemTemplate> 
 </ItemTemplate>
 </asp:Repeater>              
 <asp:Button ID="btnAddVisa" runat="server" Text="Add More Visa" onclick="btnAddVisa_Click" width="76px" />
 </div>  

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    VisaUserControl1.UserControlButtonClicked += new
             EventHandler(AddVisaControl_UserControlButtonClicked);
}

private void AddVisaControl_UserControlButtonClicked(object sender, EventArgs e)
{
    var ctrl = (VisaUserControl)LoadControl(@"VisaUserControl.ascx");
    this.rpt1.Controls.Remove(ctrl);
}

修改

这里我要添加用户控件

  public List<string> NoOfControls
    {
        get
        {
            return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];

        }
        set
        {
            ViewState["NoOfControls"] = value;
        }
    }


    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);

        GenerateControls();
    }


    private void GenerateControls()
    {
        foreach (string i in NoOfControls)
        {
            VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");

            ctrl.ID = i;
            this.rpt1.Controls.Add(ctrl);
        }
    }

    protected void btnAddVisa_Click(object sender, EventArgs e)
    {

        List<string> temp = null;
        var uc = (VisaUserControl)this.LoadControl(@"VisaUserControl.ascx");

        string id = Guid.NewGuid().ToString();
        uc.ID = id;

        temp = NoOfControls;
        temp.Add(id);
        NoOfControls = temp;
        rpt1.Controls.Add(uc);
    }

在下图中,如果单击“删除”按钮,我想删除该行

enter image description here

0 个答案:

没有答案