简体   繁体   English

事件问题C#.NET UserControl

[英]Event problem C# .NET UserControl

I have an UpdatePanel and in it a regular Panel. 我有一个UpdatePanel,并且其中有一个常规面板。 In the Panel I dynamically add simple UserControls. 在面板中,我动态添加简单的UserControls。 The Usercontrol has a Button and a Label. Usercontrol有一个按钮和一个标签。 When I click on a button in a control it removes all controls in the Panel which I have added dynamically. 当我单击控件中的按钮时,它将删除面板中动态添加的所有控件。 Can anyone help? 有人可以帮忙吗?

    int controlID = 0;
    List<Control> cc = new List<Control>();
    if (Session["ControlsCompleted"] != null)
    {
        cc = Session["ControlsCompleted"] as List<Control>;
        for (int i = 0; i < cc.Count; i++)
        {
            pnlCompletedEducation.Controls.Add(cc[i]);
        }
        controlID = cc.Count;
    }
    Controls_TestWebUserControl ct = LoadControl(@"Controls\TestWebUserControl.ascx") as Controls_TestWebUserControl;
    ct.ID = controlID.ToString();
    cc.Add(ct);
    ct.EnableViewState = true;
    pnlCompletedEducation.Controls.Add(ct);
    txtInstitutionName.Text = controlID.ToString();
    List<Control> lc = new List<Control>();
    for (int i = 0; i < pnlCompletedEducation.Controls.Count; i++)
    {
        lc.Add(pnlCompletedEducation.Controls[i]);
    }
    Session["ControlsCompleted"] = lc;

This is how I add the controls to the panel. 这就是我将控件添加到面板的方式。 I had to keep them somewhere, and i couldn't do it with the ViewState, so i used a Session, which is a bad idea. 我不得不将它们保留在某个地方,而ViewState无法做到这一点,所以我使用了Session,这是一个坏主意。

You problem that you have not recreated (for example at Page_Load) dynamically added control. 您遇到的问题是尚未重新创建(例如在Page_Load处)动态添加控件。 Make sure that control is recreated on IsPostBack 确保在IsPostBack上重新创建控件

You say that you are adding the user control dynamically. 您说要动态添加用户控件。 Are you having code like this: 您是否有这样的代码:

void Page_Load(...)    
{
     if (!IsPostback)
        // AddUserControl here.
}

You need to add the user control during every request, also postbacks, because it will not be stored in the view state that you have modified the control tree. 您需要在每个请求以及回发期间添加用户控件,因为它不会存储在修改了控件树的视图状态中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM