Adding Control to Container Control that is in User Control - How to properly initialize?
Posted
by DougJones
on Stack Overflow
See other posts from Stack Overflow
or by DougJones
Published on 2009-10-17T20:03:06Z
Indexed on
2010/05/01
3:07 UTC
Read the original article
Hit count: 327
ASP.NET
|usercontrols
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!
© Stack Overflow or respective owner