How to use delegates in ASP.NET

I have an ASP.NET project that has a form that uses a user control for the menu. I need the menu to raise an event on the parent form, so that the parent form can load data. I've coded this in Winform controls, but never ASP.NET, so... here the example. 

Related Articles

... and you 'll find more on the NET Development Menu

Step 1 — Create a custom EventArgs class
This lets you pass anything (string, ID, object, list, whatever).

UserControlAEventArgs.vb
Public Class UserControlAEventArgs
    Inherits EventArgs
 
    Public Property CustomerId As Integer
    Public Property Message As String
 
    Public Sub New(customerId As Integer, message As String)
        Me.CustomerId = customerId
        Me.Message = message
    End Sub
End Class




Step 2 — Update the UserControl to raise the event with parameters

UserControlA.ascx.vb
Public Class UserControlA
    Inherits System.Web.UI.UserControl
 
    Public Event SomethingHappened As EventHandler(Of UserControlAEventArgs)
 
    Protected Sub btnDoSomething_Click(sender As Object, e As EventArgs) Handles btnDoSomething.Click
        Dim args As New UserControlAEventArgs(42, "Hello from UC A")
        RaiseEvent SomethingHappened(Me, args)
    End Sub
 
End Class

This sends 42 and "Hello from UC A" to the parent.

Step 3 — Parent page receives the parameters

ParentPage.aspx.vb
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
    AddHandler UserControlA1.SomethingHappened, AddressOf HandleSomethingHappened
End Sub
 
Private Sub HandleSomethingHappened(sender As Object, e As UserControlAEventArgs)
    ' Now you have the parameters
    Dim id = e.CustomerId
    Dim msg = e.Message
 
    ' Do whatever the parent needs to do
    ProcessCustomer(id, msg)
 
    ' Or call UserControlB
    UserControlB1.LoadCustomer(id)
End Sub

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences