views:

1714

answers:

4

Lets say that I have a header user control in a master page, and want to change a property of the user control depending on what content page is loaded inside of the master page. How might I go about this?

Thanks!

+8  A: 

You can use two methods. The first is by using Page.Master.FindControl('controlID'). Then you can cast it to the type of your user control. The second method is by adding a <%@ MasterType VirtualPath="" TypeName=""%> tag to your aspx page. In the VirtualPath add the virtual path to the master page, and the class in the TypeName. You can then access everything with intellisense.

Shawn Simon
+3  A: 

There's one other method, and that's by making a public property on the master page that exposes the user control.

Robert C. Barth
+1  A: 

Using a public property would work. In the content page's FormLoad method, you could do something like this (VB):

Dim myMaster as MyMasterPage = CType(Page.Master, MyMasterPage)
myMaster.MyUserControl.Text = "Hello!"
Pwninstein
Using code-behind files is not a best practice. Here is attempts to get rid of them at all http://haacked.com/archive/2008/12/19/a-little-holiday-love-from-the-asp.net-mvc-team.aspx
horseman
How is it not a best practice? You're confusing ASP.NET webforms, which this question is about and ASP.NET MVC. This answer is perfectly suitable.
jwalkerjr