Wednesday 23 September 2009

Raise an Event in a Master Page from Control in the Content Page

Just a quick one because this was something that was bugging me until recently. I had a button in a repeater in a control in a page which had a master page. Now I wanted to raise an event to update something in my master page when one of that repeaters buttons was pressed. How did I do it?

Here's what I had in my control...


<asp:repeater id="rptOption" runat="server">
<headertemplate></headertemplate>
<itemtemplate>

<div class="additem">
<asp:linkbutton id="btnAdditem" runat="server" text="Add to Basket" commandargument="'<%#Eval(">' CommandName="OfferID" />
</asp:linkbutton></div>

</itemtemplate>
<footertemplate></footertemplate>

My code behind needed a new public event declaring which I will be seen from the page containing the control....

Public Event CartAdded(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs)

Now in the event raised from the repeater control I need to raise this new event so that the page can find out the user just clicked that button.

Protected Sub rptOption_ItemCommand1(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptOption.ItemCommand

RaiseEvent CartAdded(source, e)

End Sub


Now if you go back to your page you can refer to your controls new event. Something like this should do:

Protected Sub productBuyOptions_CartAdded(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles productBuyOptions.CartAdded
Master.UpdateCart()
End Sub

In this situtation my master page has a public sub called UpdateCart which I am calling.

One more thing before this works, I believe you have to put a reference back to your master page in your content page.

<%@ MasterType VirtualPath="~/yourMasterPage.master" %>

This will let you reference public methods and properties from your content page. Hooray!