How do I access MasterPage functionality from an App_Code class?

D

dawg1998

I am trying to access a label located in a MasterPage from a class
located in my application's App_Code folder. The problem seems to be
that the class cannot communicate with the MasterPage due to a lack of
reference to it. How do I supply a reference to the class so that it
can populate the label? My code is below...

*The reason I am doing it this way, is that I want the typical code
used to supply a string to the MasterPage label to be hidden away in
case I change it later on. Using an object to send a string to the
class allows me to do this without committing each and every page to a
specific method.*

`````````````````````````````````````````````````````````````
1) So, in my MasterPage I set up a simple Label control:

<asp:label id="lblLabel" runat="server" />

2) In a class stored in App_Code I set up a procedure to populate the
label in the MasterPage:

Public Namespace CustomClasses
Public Class MessageMaker
Public Sub CreateMessage(ByVal strMessage As String)

Dim lblError As Label
lblError = Master.FindControl("lblLabel")
lblError.Text = strMessage

End Sub
End Class
End Namespace

In a content page, I want a procedure to create that creates a message
in the MasterPage label. This will be used for all system messages sent
to the user.

Dim objMessage As New CustomClasses.MessageMaker()
objMessage.CreateMessage("This is a Test")
 
G

Guest

You may find it easier by changing the pattern:

Public Function CreateMessage(ByVal strMessage As String) As String
strMessage="Here it is" & strMessage
return strMessage
End Function

In your page,


Dim objMessage As New CustomClasses.MessageMaker()
Dim lbl As Label = Master.FindControl("label1")
Dim msg as String =Master.FindControl(objMessage.CreateMessage("This is a
Test")
lbl.Text=msg

Otherwise, you would need to figure out a way to pass the page context to
your class. You *CAN* do this if absolutely necessary:

Public Function CreateMessage(ByVal strMessage As String, ByRef Page as
System.Web.UI.Page) As String
' etc.
End Function



Hope that helps.
Peter
 
D

dawg1998

Peter:

Thanks for the reply.

My goal, though, is to eliminate the "Master.FindControl('label1')" bit
of code from my content page and move that to the class in App_Code.

So, yes, I guess my goal is to pass the page context to the class. Is
the method you detailed a costly one in terms of resource usage?

rb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top