views:

167

answers:

2

I have an UpdatePanel and in it a regular Panel. In the Panel I dynamically add simple UserControls. The Usercontrol has a Button and a Label. 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.

A: 

You problem that you have not recreated (for example at Page_Load) dynamically added control. Make sure that control is recreated on IsPostBack

Dewfy
A: 

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.

Pete