C# – Programmatically adding a user control in ASP.NET

asp.netcuser-controls

I have a user control that needs to load a child control when a button is clicked.
The trouble is that it has to request the control from another class.

So in the button click event, I call the function to get me my control, and add it to the page, like this:

UserControl ctrl = ExampleDataProvider.GetControl(some params...);
myDetailPane.Controls.Add(ctrl);

The GetControl method looks like:

public static UserControl GetControl(some params...)
        {
            ExampleDetailPane ctrl = new ExampleDetailPane();
            ctrl.Value = "12";
            ctrl.Comment = string.Empty;
            return ctrl;
        }

This isn't working due to the page's lifecycle – the Page_Load of the child control gets fired and its controls are null.

I kind-of know that my approach is wrong and why, but don't know the best way to go about fixing it! Could anyone help?

Best Answer

Dynamic controls must be re-created on every postback, this Article is a good link about how to persist dynamic controls and their state.

Related Topic