Subscribe

RSS Feed (xml)

Raising Events from a User Control

User Controls support events using the same syntax as other classes in the .NET
Framework. Simply declare the event using the following syntax.In the User Control’s <script runat=”server” /> block or codebehind:
Public Event MultipleReached(ByVal sender As Object, ByVal e As EventArgs)
Public Overridable Sub OnMultipleReached(ByVal e As EventArgs)
RaiseEvent MultipleReached(Me, e)
End Sub
The page can wire up the event by specifying a function for the OnMultipleReached
attribute of the User Control, as follows.The ASPX page:
<uc1:Recipe0206vb id=”Recipe0206vb1” runat=”server” Multiple=”5”
OnMultipleReached=”MultipleReached”></uc1:Recipe0206vb>
The User Control needs to raise the event by calling OnMultipleReached, which in this
case it does every Nth time a counter is incremented.
In the User Control’s <script runat=”server” /> block or codebehind:

‘ if number of hits is a multiple of Multiple, raise event
If Application(“count”) Mod Multiple = 0 Then
OnMultipleReached(EventArgs.Empty)
End If

Finally, in the page, you can specify which action to take in response to the event that
the event handler function specified.
In <script runat=”server” /> block or codebehind:
Sub MultipleReached(ByVal sender As Object, ByVal e As EventArgs)
Message.Text=”Congratulations! You were the 5th visitor!”
End Sub



The syntax for raising and handling events is quite different for C# than for VB.NET.
The C# version of this technique is available from this book’s Web site.

No comments:

Archives

Variety in the Web World