Adding Control to Container Control that is in User Control - How to properly initialize?
- by DougJones
Let's say I have a user control MyUserControl, which has a container control (it's a server control, but it could just be a Panel) and a dropdownlist. The dropdownlist is not in the container control initially. In it's code-behind, I am overriding OnInit and creating the user control, which includes populating a dropdownlist and adding that dropdownlist to my container control. I have a public property Year, which is an int. Based on the value of Year, I want to populate the dropdownlist. The problem is that in OnInit, year is always 0.
On the page Init, I am setting year, but that doesn't run until AFTER the control's Init runs. If I try to set the value on PreInit on the page, the page hasn't initialized the control and I get invalid null reference when setting a value to the control.
My question is: How can I properly initialize the control? How can I set the value on the page, before the control actually gets initialized?
If I move the control's code to OnLoad, it'll work until I have to do a postback. In this case I need to, though!