Search code examples
vb.netaddhandler

Object name of that started subroutine using add handler


My problem is that when the subroutine runs I don't know which button caused it to be triggered how can I find this out. The variable count needs to be replaced with the delete button number that was clicked. I cannot have a separate subroutine for each button as I don't know how many the user needs to be added to the form on each occasion.

    Dim delete1 = Sub()
        .Remove(label1(count, 1))
        .Remove(combo1(count, 1))
        .Remove(label1(count, 2))
        .Remove(combo1(count, 2))
        .Remove(label(count, 3))

                 End Sub

    For counter = 1 To count
        AddHandler MyClass.button1(counter).Click, delete1
    Next

Solution

  • You can get it from the sender argument:

    Private Sub delete1(sender As System.Object, e As System.EventArgs)
    
        Dim curButton As Button = DirectCast(sender, Button) 'Button you clicked
    
    End Sub
    

    Note that the code to add the aforementioned function directly (without delegate) is:

    AddHandler MyClass.button1(counter).Click, AddressOf delete1