5
votes

I have a user control that will dynamically add other user controls to it, depending on user preferences. I'm having problems adding the controls with the overloaded LoadControl method.

I tried doing this:

ddControl = typeof(DropDownControl), new object[] { testData, FilterModel.Models[i] });

However, none of the controls in ddControl were initialized and when I tried to set the datasource to the combobox it contains, it exploded. I pass in a model and a datasource to the constructor which sets properties, default values, etc. Do I have to create a LoadModel() method to load the model values after I create the control like

(DropDownControl)LoadControl("~/WebUserControls/DropDownControl.ascx")

or can I do it all through the constructor somehow while declaring it dynamically?

If this isn't clear, let me know how I can make it so. Thanks!

1
webforms & usercontrols are allergic to constructor injection. Your best bet is to add a method that you call after LoadControl to do the injection. - Simon Halsey

1 Answers

0
votes

You can use PlaceHolder to add these user controls dynamically and do other operations by exposing a method for doing so, and this way you have more control over everything without interfering into life cycle of your control.

Don't use constructor use Properties and Methods instead.