How to reference a Master Page from a user control?

限于喜欢 提交于 2019-12-03 05:35:47
Dan Herbert

Try Page.Master.

Whatever whatev = (Whatever)Page.Master;

You'll have to make sure you add the proper using statements to the top of your file, or qualify the Master page type inline.

One potential gotcha is if this control is used by a different page whose master page is NOT the same type. This would only get caught at runtime.

Have you tryed Page.FindControl("name") on the usercontrol?

The best way to do it that I've found is actually to build a custom class that is based off of UserControl, give it a Master property with a get accessor that fishes through the this.Page.Parent until it stops encountering master pages (If you are nesting, this step is unnecessary otherwise) and then return that web control as the type of the master page you want to use. Then, when you add a new user control, change it's base class to the name of your custom class. The .Master property will be accessible and cast properly as the master page you want it to use.

In VB all I needed to do was change this:

Dim lAuthLevel As Integer = Master.MasterContact.AuthenticationLevel

to this:

Dim lAuthLevel As Integer = CType(Me.Page.Master, main).MasterContact.AuthenticationLevel

So all references of Master become Ctype(Me.Page.Master, typeofMaster)

Where is in this case the word "main" - get that from the declaration at the top of the master page. e.g.

So "main" in this case :)

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