How to access a user control in a masterpage from a content page?
Asked Answered
A

4

7

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!

Aland answered 19/12, 2008 at 22:5 Comment(0)
P
14

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=""> OR <%@ MasterType TypeName=""%> tag to your aspx page. In the VirtualPath add the virtual path to the master page, or the class in the TypeName. You can then access everything with intellisense.

Pencil answered 19/12, 2008 at 22:16 Comment(2)
The MasterType directive should use either VirtualPath, OR TypeName, but is unable to use both.Ludwog
@Ludwog is correct and I've edited the answer to reflect his comment.Danford
H
6

first find the user control in the masterpage as below.Then find the control you need to access their property.

UserControl uch = Page.Master.FindControl("ucHeader1") as UserControl;
PlaceHolder phProxylist= ucHeader1.FindControl("phProxy") as PlaceHolder;
DropDownList ddlproxylist1 = ucHeader1.FindControl("ddlProxyList") as DropDownList;
phProxylist.Visible = false;

Hope this helps.

Handling answered 21/2, 2011 at 18:29 Comment(0)
P
4

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

Pistol answered 19/12, 2008 at 22:25 Comment(0)
R
1

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!"
Rastus answered 20/12, 2008 at 2:20 Comment(2)
Using code-behind files is not a best practice. Here is attempts to get rid of them at all haacked.com/archive/2008/12/19/…Pained
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.Carlsen

© 2022 - 2024 — McMap. All rights reserved.