views:

81

answers:

1

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!

A: 

Set the properties in PreRender of your user control.

And I am assuming you are registering the User Control properly:

Check the accepted answer here >>>

Shankar Ramachandran
I'm actually adding controls to another control on the user control. I have a reason for this, but let's say I have a Placeholder control and I'm adding the controls (including this dropdownlist) to it in OnInit. If I added them in prerender the structure wouldn't be properly created when the ViewState is set for the control. So...the dropdownlist would have a selectedindex of 0 after it gets bound on postback, even though the user selected index 7.
DougJones
@LionelHutz It would be great if you gave the exact scenario.And edited your question to reflect that.
Shankar Ramachandran
Took your suggestion. Thanks for the help.
DougJones