How to set user control properties before getting visualization?

I have a user control (uc) on the page. uc provides some properties that are set in the Page_Load () event of the parent page and should be read while user control is loading.

Looks like uc fires Page_Load () before any properties are set from the parent page.

In what event should I set the uc properties so that it can use these properties as they are rendered?

I am using ASP.NET 3.5 and C #

ps I just dug the solution from my old code:

in the Page_Load control, do:

Page.LoadComplete += delegate { LoadTheControl(); }; 

I would still like to hear your ideas.

+4
source share
5 answers

You can access the OnPreRender property without any tricks.

+6
source

I just ran into this problem this afternoon.

I created a public method in UserControl called LoadData () and called it from Page_Load of my hosting page after setting the property that the data depends on.

Added - sample code

In a user control:

 public property SomeProp {get, set}; public void LoadData() { // do work } 

and in the PageLoad page on the hosting page

 myControl.SomeProp = 1; myControl.LoadData(); 
+3
source

If you place usercontrol on the page declaratively, just set the property there.

 <cc1:myUserControl MyProperty="1" /> 

If you add controls to the page dynamically, simply set the property before adding the control to the hosting page's control collection. None of the lifecycle events for the control light up until you call Page.Controls.Add(myUserControl) .

If it is not possible to avoid the setup you got right now, and the parent should do some logic in Page_Load, and UC should be there already, then I would suggest that David Stratton wrote, but in my experience this is usually standardized as Initialize() or Init() .

+3
source

Well, not a single answer helps me. But when the manual set of properties in the InitComplete () event, everything works fine. Now my user control has been enabled to read the property AFTER I set the property before.

+1
source

I ran into a similar problem: -

I first add the UserControl dynamically, and then try to assign values ​​to the internal controls (text box inside the user control). Using any event, such as INIT or LOAD, the control gives me the exception of the link , because, as you can see from the step-by-step code, the controls have not yet been created.

Later, I discovered that this problem only occurs if I declare the control through the dim statement:

 Dim MyControl as new MyUserControl Me.Panel1.Controls.add(MyControl) MyControl.SetLabelText("My Name") 'Uses a method to set the label text on load. 

On the other hand, if I use the control as follows, it works fine:

 Dim MyControl as MyUserControl = LoadControl("MyUserControl.ascx") Me.Panel1.Controls.add(MyControl) MyControl.SetLabelText("My Label Text") 
0
source

All Articles