We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
As we all know whenever we build an ASP.NET application with a MasterPage, all the controls receive a prefix such as “ctl00$<ContentPlaceHolderID>$<NameYouGaveToControl>” to their names according to their place in the page hierarchy. That is done in order to prevent from two controls to have the same ID on the same page.
We encounter a problem whenever we want to seek a control. Lets assume we have a page with a control named “LoginButton”. Normally we would use the following command:
This will work only if we don’t have a MasterPage present. If a master page is present we must add the prefix in order for this to work, so the line will look like this:
That will also work. But we don’t want to see hard coded strings like “ctl00$ContentPlaceHolder1″ because if tomorrow we will change the hierarchy of the page, change names or something like that, everything will fall apart.
There is a nice way to make this more robust and simple to maintain. My solution is to save a variable that holds a reference to the closest ContentPlaceHolder. The rational is that a Page does not need to know its place in the hierarchy of pages in the application, but it should know the closest ContentPlaceHolder above it. We have to create a manager class that will supply the right Place Holder, that way if we change something, we only need to make the adjustments in one place.
Manager will do something like this:
ContentPlaceHolder C = (ContentPlaceHolder)this.Page.Master.FindControl("ContentPlaceHolder1"); Application["Page1Holder"] = C;
Of course you can store the reference wherever you see fit (Static Class and so on). When we need to access the control we will do this:
ContentPlaceHolder c = (ContentPlaceHolder)Application["Page1Holder"]; Control b = c.FindControl("LoginButton");
And that’s that. No need to know where we are in the page hierarchy.
Tags :.NetASP.NetC#ContentplaceHolderFindControlHierarchyManagerMasterPagePagePrefixWeb Application
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd