I’m dynamically loading user controls adding them to the Controls collection of the web form.
I’d like to hide user controls if they cause a unhandled exception while rendering.
So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class.
Did some googling around and it doesn’t seem promising. Any ideas here?
mmilic, following on from your response to my previous idea..
No additional logic required! That’s the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! 🙂
OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some very rough code but the concept is there and it seems to work.
APOLOGIES FOR THE LONG POST
The SafeLoader
This will basically be the ‘bubble’ I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering.
And Some Controls..
Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don’t give a crap. These will be replaced with your custom controls..
BadControl
GoodControl
The Page
OK, so lets look at the ‘test’ page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc..
Page Code-Behind
Thoughts
OK, I know what you are thinking, ‘these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you’re messing with my mojo’.
OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend.
Finally..
Again, sorry for the long post, but I wanted to get the code here so we can discuss this 🙂 I hope this helps demonstrate my idea 🙂
Update
Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I’ll leave that to you 😉
Enjoy!