1

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.

I'm using

label1.InnerText = (string)GetLocalResourceObject("default");

To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.

Am I right about how resx files work or does it only work for Pages?

I have the same code working on an aspx page.

Morgeh
  • 679
  • 3
  • 11
  • 27
  • I updated my answer based on your comment – David Jan 08 '10 at 19:19
  • I understand where your coming from but the idea of the resx is that I can globalise the content if so placing the value in the config isnt really and option. – Morgeh Jan 08 '10 at 19:53

3 Answers3

4

When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.

protected string HttpContextGetLocalResourceObjectAsString(string message)
{
  string path = HttpContext.Current.Request.Path;
  return (HttpContext.GetLocalResourceObject(path, message) as string);
}

Now you can do

label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • This solution works perfectly if you want to store the resource string inside the page's local ressource file. If you want to keep it separate from the page (e.g. if you don't want to repeate the strings for each page but define it only once - say for a menu control), I have described a different solution [here](http://stackoverflow.com/a/15339537/1016343). – Matt Mar 11 '13 at 13:34
0

Per the documentation:

Gets a page-level resource

http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx

Edit- added

It may be less work to just add the string to the web.config and grab it from there.

<configuration>
  <appSettings>
    <add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
  <appSettings>
...

referenced as follows:

logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];

Of course, you'll need a reference to the System.Configuration dll.

David
  • 72,686
  • 18
  • 132
  • 173
  • no joy gives me the following compilation error: Cannot access protected member 'System.Web.UI.TemplateControl.GetLocalResourceObject(string)' via a qualifier of type 'System.Web.UI.Page'; the qualifier must be of type 'Controls_NavigationMenu' (or derived from it) – Morgeh Jan 08 '10 at 18:53
0

A year or so later, but i think this is what you're after?

var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());

Mark answer if that's the one!

Cybermaxs
  • 24,378
  • 8
  • 83
  • 112