Handling Master Page Click Events in the Content Page
I had to try something new the other day to solve a problem, setting the Click Event Handler of a button on a Master Page in the Content Page. Honestly I have never had the need, or at least not realized that I needed this functionality up to this point so I was a little hesitant. Needless to say I figured it out and pretty quickly, at least a workable solution.
So the problem I had to solve was how to handle a LinkButon Click event from within the content page for a LinkButton on the Master Page. The LinkButtons need to be displayed on every page the same way, but each page needed to process some unique business logic on each content page, so I really needed to handle the click event in the content page.
I often create public properties to provide access to variables on Master Pages. I also do this with Cross-Page Postbacks to provide access to variables and controls. So I thought this would work.
This is the code that defines the property in the Master Page for the LinkButton lnkbFromMasterPage.
VB
Public
ReadOnly
Property
lnkbFromMasterPage()As
LinkButton
Get
Return
lnbFromMasterPage
End
Get
End
Property
C#
Public
LinkButton
lnkbFromMasterPage(){
Get {
Return
lnbFromMasterPage;
}
}
The next step is to reference the Master Page as a casted object in the Content page. This can be done easy enough by accessing the MasterPage object of the content page and casting it to the class for our Master Page. Here the class defined for the Master Page is CustomMasterPage.
VB
Dim
cmpAs
CustomMasterPage =CType
(Master, CustomMasterPage)C#
CustomMasterPage cmp =
(
(CustomMasterPage)(Master));Now we can access any Public properties, methods and members of our CustomMasterPage class. So here was the magic, would I be able to handle the button events in the Content Page? Of course I can!
You simply need to define the event handler in your Content Page, I do it in the PageLoad event handler.
VB
If
Not
IsNothing(cmp)Then
AddHandler
cmp.lnkbFromMasterPage.Click,AddressOf
lnkbFromMasterPage_Click
End
If
C#
If
(!(IsNothing(cmp))) {
cmp.lnkbFromMasterPage.Click += New EventHandler(lnkbFromMasterPage_Click);
End
If
Later in my code I define the actual method to handle the event.
VB
Protected
Sub
lnkbFromMasterPage_Click(ByVal
senderAs
Object
,ByVal
eAs
System.EventArgs)
'Perform Business Logic Here
End
Sub
C#
Protected
void
lnkbFromMasterPage_Click(Object sender
, System.EventArgs e){
'Perform Business Logic Here
}
That is all there is to it. The same architecture works for User Controls as well, since that is really what a Master Page actually is. I was satisfactorily surprised at how easy this was, not to mention my first thought on how to solve this problem.