简体   繁体   中英

Firing an event to the parent page when a user control finishes loading in ASP.NET

I am working with an ASP.NET project that was created by a team elsewhere in the company. One of the pages that I am working with features a userControl that queries the database to populate a generic field. The information from this query is then used by the parent page (that is, the page that contains the userControl) to set the selectedIndex of a dropdown.

The issue that I am having is that the parent page loads before the userControl, which means that the parent page loads before the results of the query are available. As a result, the selectedIndex of the dropdown is only ever set to a default index.

Based on jrista's answer to ASP .NET: when UserControls loads? , I understand that the page.OnLoad event fires before the userControl.OnLoad event. I also understand that there is no OnLoadComplete event for user controls, which I was hoping I could use to make an event that fires on the parent page when the user control finishes loading.

I've heard that the Pre-Render event can be used to the same effect ( based on this question over on the asp forums ), but is this the only approach? Is there a better way to fire an event from a userControl to the parent page when the user control finishes loading? Or is this simply not a good practice and would I be better to somehow change the code to avoid this situation?

Start by creating an interface that your page will implement like so:

 public interface INotifyChildLoaded
 {
     void OnUserControlLoaded(Control control);
 }

Then, implement that interface on your page

 public class MyPage : Page, INotifyChildLoaded
 { 
     public void OnUserControlLoaded(Control control) { ... }
     ....
 }

Finally, during your user control load event, call the method:

 public void MyControl_OnLoad(object sender, EventArgs e) 
 {
     ....
     (Page as INotifyChildLoaded).OnUserControlLoaded(this);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM