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

情到浓时终转凉″ 提交于 2020-01-22 15:17:08

问题


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!


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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!"


来源:https://stackoverflow.com/questions/382358/how-to-access-a-user-control-in-a-masterpage-from-a-content-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!