Search code examples
winformsvisual-studiobasicsender

Visual Basic sender not coming back as control


I have a windows application with 2 forms.

frmMain has a button (btnEditAgent) on it that opens frmEditAgent:

Public Sub btnEditAgent_Click(sender As Object, e As EventArgs) Handles btnEditAgent.Click
    frmAgentEdit.ShowDialog()
End Sub

Then on frmEditAgent load:

Private Sub frmAgentEdit_Load(ByVal sender As Object, e As EventArgs) Handles MyBase.Load

    MsgBox(sender.Name, vbOKOnly, "verify")

End Sub

The sender comes back as "frmEditAgent" and not "btnEditAgent"

I do not understand why this is happening. In order for the rest of my code to work I need to know which button opened frmEditAgent. Why is sender referring to the same form?


Solution

  • The sender of the Load event is the Form that was just loaded. The semantics of sender wouldn't make sense otherwise.

    Think of it this way: the button opens the form, but the form does its own loading, and so calls its own Load event with itself as the sender.

    If you want to know which button opened the form, then you can add an instance variable to your dialog form's class and then just set that variable in btnEditAgent_Click.

    frmAgentEdit can then just use that instance variable to know which button caused it to be opened.