enter code here
I am trying to assign a value to label in a Master Page using vb.net (not my first language-lol). I have followed info from these two references on how to access content from masterpage:
1.[https://msdn.microsoft.com/en-us/library/c8y19k6h(v=vs.90).aspx][1]
2.[nullreferenceexception was unhandled by user code in Master Page
I am getting Null Reference Exception on BUT ONLY when I try to call the method I created for it from another class. It works fine when I call it from the same class the method is in. I wrote a method from the starting page/class, WebForm1:
Public Sub PageIdentity(ByVal pageId As String)
' Gets a reference to a Label control inside a ContentPlaceHolder
Dim mpContentPlaceHolder As ContentPlaceHolder
'Dim mpTextBox As TextBox
Dim mpLabel As Label
mpContentPlaceHolder = CType(Master.FindControl("MainContent"), ContentPlaceHolder)*'Null Reference Exception here*
If Not mpContentPlaceHolder Is Nothing Then
mpLabel = CType(mpContentPlaceHolder.FindControl("lblPageIdentifier"), Label)
If Not mpLabel Is Nothing Then
mpLabel.Text = pageId
End If
End If
End Sub
when I call this function from another class in page load like this it throws null ref ex:
Dim oWebForm1 As WebForm1 = New WebForm1()
oWebForm1.PageIdentity("SomeText")
I must be doing something wrong in creating the instance? I tryed writing it as a Public Shared Function first but that created other problems. Can anyone help?
UPDATE: @Joey I replaced the commented line of code below as you suggested and put the sub in the master page code behind, Site1.Master.vb:
'mpContentPlaceHolder = CType(Master.FindControl("MainContent"), ContentPlaceHolder)
mpContentPlaceHolder = CType(Me.FindControl("MainContent"), ContentPlaceHolder)
I also ensured that the page directive on other pages included:
<%@ MasterType VirtualPath = "~/Site1.Master" %>
On a test page, I called the sub like so:
Dim _SiteMaster As MasterPage = TryCast(Me.Master, MasterPage)
_SiteMaster.PageIdentity("SomeText")
I am getting blue squiggly line error, message: "PageIdentity is not a member of System.Web.UI.MasterPage"
The Master page inherits like this:
Public Partial Class Site1
Inherits System.Web.UI.MasterPage
The page calling the sub inherits like this
Public Class WebForm1
Inherits System.Web.UI.Page