I would like some code to execute at the ‘preload’ stage of my usercontrol’s lifecycle. However the preload event is only available on the Page object. So, I added the following method to my usercontrol:
Private Sub Page_PreLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Page.PreLoad
However, I know get the compile error: ‘Handles clause requires a WithEvents variable defined in the containing type or one of its base types’
As the Page property is inherited from UserControl I don’t see how this can easily be done.
Any help gratefully received!
I apologize for giving a C# example but I can’t remember how to do it in VB…Anyway, in your UserControl’s Init you could explicitly assign your Page_PreLoad method as the handler for the PreLoad event of the UserControl’s Page property instead of using the ‘Handles’ syntax in the method declaration. What your example is doing is trying to assign an event handler to an event on the UserControl object for an event that the UserControl object doesn’t raise. As you noted, UserControl doesn’t inherit from Page, which is where the PreLoad event lives. UserControl does, however contain a Page object as one of its properties, which in turn exposes PreLoad as an event to which you can assign a handler. Anyway, this compiles and approaches what it sounds like you are looking for (using C-style comments to preserve WMD syntax highlighting).
I’m not sure if that serves your purpose–as Stephen Wrighton indicated above, there may be a better way with one of the different events in the page lifecycle. However, building on what he said, this should work because the control’s OnInit is called in which the event handler assignment is made, then the Page’s OnLoad event is raised and then the event handler within the control is executed.