Find a texbox control or label control on a master page from an inner page

I noticed that this one seems to catch a good few people out - including myself when I was starting out with Master Pages. If you have an aspx page that sits in your Master Page you might have a need of populating a label or a textbox (or other control) with some value. To do this you can simply use the following code to tell .net to find your control on your master page. In the example below I am looking for a Literal control but you can easily change this to TextBox or Label or whatever you want:

Literal ControlIDToFind = (Literal)this.Master.FindControl("ControlIDToFind");

Just change the ControlIDToFind to the name of your ID you want to grab and then you can use it just like you would a normal .net control on your child page. So using the example above, if I wanted to output text into my ControlIDToFind literal which is in my MasterPage I would use the following code in my Child Page:

ControlIDToFind .Text = "some text about how great you are!";

 It's only a small 2 line thing but you'd be surprised how often this catches people out. Below is a small list of items you can find using the above tips, hope it helps!

//find a dropdown in your masterpage and get it's selected value
DropDownList CountryList= (DropDownList)this.Master.FindControl("CountryList");
string SelectedCountryList = CountryList.SelectedValue;
//find a textbox in your masterpage and get it's value
TextBox EmailAddress = (TextBox)this.Master.FindControl("EmailAddress ");
string EmailAddress = EmailAddress.Text;
//find a label in your masterpage and get it's value
Label EmailAddress = (Label)this.Master.FindControl("EmailAddress");
string EmailAddress = EmailAddress.Text;

C#
blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets