Accessing Global Resource From ASP.NET Custom Controls
To programmatically get global resource object from code-behind for Page or UserControl, we usually use the GetGlobalResourceObject() method, passing in the resource name and the key. You’ll be fine until you need to call it from other than a Page or a UserControl or anything that does not inherit from TemplateControl.
I that need to use it from a custom control, which inherits from CompositeControl, which has no TemplateControl anywhere in it’s inheritance tree. Although I can access it’s Page property which holds the reference to the containing Page object, I cannot do Page.GetGlobalResourceObject() since that method is marked as protected.
Through some blog posts, I’ve been left with assuming that this is a serious design flaw. Why in the world that it is not marked as public?! After trying several hacks and finding leeways to get around this, I finally find out that you can get the similar method from HttpContext.
Just a simple call to HttpContext.GetGlobalResourceObject()! It’s a static method, so you can call it anywhere. That simple!
Working with resources is tricky business, since some of the classes are generated and compiled at runtime by the ASP.NET engine. Even though Visual Studio can assist you by “pre-compiling” them and let them appear in IntelliSense, sometimes you’ll just wonder where the heck that some class or some method comes from!
Trackbacks
Trackbacks are closed.

