Toars I will smile to the world ^o^

17Aug/090

How to access controls in Master Page / Strongly typed Master Page

It is very simple for a page to access the controls in its Master Page.

For example, we can use this way:

((Label)(Master.FindControl(“LblTitle”))).Text = “My Application”;

or

(Master.FindControl(“LblTitle”) as Label).Text = “My Application”;



Can you see that? first, it is not very clean look, second, no intellisence for the LblTitle (the control ID). I don’t like this way of accessing the controls in the Master Page.

I would rather to make the Master Page strongly typed, and create properties or method in the Master Page.

In order to make the Master Page strongly typed, we need to declare the MasterType in the Aspx pages. For example:

<%@ MasterType virtualpath="~/MasterPages/Support.Master" %>
11Aug/091

How to make ASP.NET resources strongly typed

In multi-language supported applications, for different languages, we need to have different localized resource files, such as Common.resx (the default fallback resource file) and Common.en-GB.resx (the language specific resource file).

If we don't override the default classes ResourceProvider and ResourceProviderFactory, we have to store all the resource files either in the App_GlobalResources folder or App_LocalResources folder. Or even we have our own resource provider, we still need to access the resources using this way in Aspx pages:

<%$ Resources:Common, LblYourName %>



Or access the resources in the code-behind pages:

ResourceProvider rp = new ResourceProvider();
rp.GetObject(resourceName, culture);



The biggest disadvantage of accessing resources in those ways is you do not have the intellisense nor the compile time error hint.

In order to avoid this, we can make the resources strongly typed, then the resources can be accessed as properties. When you mistype the resource names, you get the error hint immediately.

How to achieve this? It is very simple. Locate the resource files, for instance, Common.resx, and then right click the file, choose Properties, and fill in Custom Tool textfield with PublicResXFileCodeGenerator. At the meantime, in the dropdownbox Build Action, choose Embedded Resource. And recompile the project.

You are ready to go.