Friday, July 11, 2008

Accessing a variable in your masterpage from an .aspx page.

If you have a regular .aspx page that inherits a master page and you want access to some variable(s) in that masterpage, consider the following.

Say you currently have a variable in your masterpage dim'd as such:

Dim foo As String = "bar"


In order to access this foo variable in any of your pages that inherit this masterpage, simply add the following code in your masterpage.

Public Property foo() As String
  Get
    Return foo
  End Get
  Set(ByVal value As String)
    foo = value
  End Set
End Property


Now, in your regular .aspx content page you can gain access to the foo variable by doing the following in your Page_Load sub:

Dim newFoo As String = CType(Me.Master, MasterPages_Home).foo()


Conversely, you can change foo's value (or "set" it) by doing:

CType(Me.Master, MasterPages_Home).foo() = "new value"


In this example, MasterPages_Home is the class name of our MasterPage.

No comments: