Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code "one sub for many subs" in VB.NET?

Tags:

vb.net

I have n Labels on Form, e.g: Label1, Label2,..., Labeln. Normally, when I write Click event for all Labels:

    Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
        Msgbox "1"
    End Sub

Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label2.Click
    Msgbox "2"
End Sub

Private Sub Labeln_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Labeln.Click
    Msgbox "n"
End Sub

Writting is very complex when n is large!

Now, I want to write the code simply to click to Lablei and generate "i" (one proceduce to many proceduces). How to handle it? Thanks in advance.

like image 307
Newton Isaac Avatar asked Nov 25 '25 15:11

Newton Isaac


2 Answers

Private Sub Labeln_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
       Handles Label1.Click, Label2.Click, Label3.Click '...
    Dim l As Label = DirectCast(sender, Label)
    Msgbox l.Name
End Sub

If n is very large, skip the Handles portion of the method and do this in your form load:

For Each l As Label in Me.Controls.OfType(Of Label)()
    AddHandler l.Click, AddressOf Labeln_Click
Next
like image 112
Joel Coehoorn Avatar answered Nov 28 '25 14:11

Joel Coehoorn


You can dynamically assign the event handlers when you create your labels using AddHandler:

Sub test()
    Dim label1 As New Label()
    AddHandler label1.Click, AddressOf HandleLabelClick
    Me.Controls.Add(label1)
End Sub

Here's the event handler:

Sub HandleLabelClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MsgBox(DirectCast(sender, Label).Name)
End Sub
like image 20
rory.ap Avatar answered Nov 28 '25 14:11

rory.ap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!