Wednesday, April 8, 2009

Raising Events From User Controls

Given a simple button in a usercontrol, here is the code behind

Partial Public Class WebUserControl
Inherits System.Web.UI.UserControl

Public Event MyEvent As System.EventHandler

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
RaiseEvent MyEvent(Me, New EventArgs())
End Sub
End Class


And in the code behind aspx page


Partial Public Class _Default
Inherits System.Web.UI.Page

Dim WithEvents uc As WebUserControl

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub myControl_MyEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles uc.MyEvent
'...'
End Sub

End Class


On aspx page

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication37._Default" %>
<%@ Register Src="~/WebUserControl.ascx"  TagPrefix="uc" TagName="mycontrol" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <uc:mycontrol ID="myuc"  runat="server" OnMyEvent="myControl_MyEvent"  />
    </div>
    </form>
</body>
</html>