Today I had to figure out how to access a label control on the masterpage my page was using. It isn't quite as straightforward as one might imagine, but still not difficult. For this, I am using C# 2008 (v3.5)
For this particular page, I have an <asp:Label/> control on the line immediately following the <form> tag in the master page. This label is going to be used for displaying general messages, errors, warnings, etc from within the code of pages using it. The problem is that you cannot just do something like "this.Master.FindControl("LabelDisplay").Text = "Some Text Here"; (At least not yet).
To find it you need to walk back up inheritance chain from your present location, to the page that has the control, then find the reference to the target control, cast that reference as the appropriate type (in this particular case Label), then you have access to all of its properties and methods.
Here is the code to do this:
((Label)this.Master.Controls[1].Controls[1].FindControl("MessageDisplayLabel")).Text = "here we are";
Posted
Nov 13 2008, 05:47 PM
by
dacrowlah