I’m adding a User Control for each record pulled up in a data reader, here’s the basic loop:
while (dr.Read()) { ImageSelect imgSel = new ImageSelect(dr['Name'].ToString()); myPanel.Controls.Add(imgSel); }
The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.
I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.
I’ve run the above code in the Page_Init and Page_Load events, both with the same result.
EDIT: Ok so I’ve switched to using LoadControl(‘….ascx’) to get my control instance, which is now working. But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?
EDIT 2: Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.
EDIT 3: After trying this method both with and without the constructor. I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.
Update: As Steve pointed out, the overload of LoadControl that uses the type won’t take into account the controls in the ascx. This is also mentioned in this answer: Dynamically Loading a UserControl with LoadControl Method (Type, object[]).
As I mentioned before, the get/set are more in line with the asp.net model, so I recommend using that with the LoadControl variation that receives the user control path. That said, the Steve’s version is an interesting alternative: http://www.grumpydev.com/2009/01/05/passing-parameters-using-loadcontrol/.
My take is the LoadControl with type is meant to be used with web custom controls instead.
If it is an user control you should use LoadControl(usercontrolpath) to get the instance of the user control.
You can use a constructor by doing:
Notice that depending on the project model you are using, you need to add a Reference to the aspx to use it with the typeof variation:
Ps. I usually use the set/get for controls as I find them more in line with the asp.net model