views:

737

answers:

3

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.

A: 

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 Stratton
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
+1  A: 

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