alwaysVBNET
alwaysVBNET

Reputation: 3310

How can a called form get the caller ID or tag of the calling control

I have a button on my form FormA which is called search. When this button is clicked the frmSearch loads. I want to make the frmSearch dynamic so if it called by the button 'Search Employee' it searches only employees etc. Is there a way which I can input the caller's ID or tag into frmSearch instantly?

This is what I have at the moment but it only identifies the caller control. (I could instantiate a global variable and read it from frmSearch but I'm wondering if there's a better way):

  Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        frmSearch.Show()

        Dim btn As Button = CType(sender, Button)
        MsgBox(btn.ToString)
        MsgBox("you have clicked button " & CType(CType(sender,  _
   System.Windows.Forms.Button).Tag, String))
    End Sub

Upvotes: 0

Views: 1538

Answers (1)

dbasnett
dbasnett

Reputation: 11773

In formA your code will look something like this

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim caller As String = DirectCast(sender, Button).Name
    Dim f As New frmSearch(caller)
    f.Show()
End Sub

Note that I am not using the default instance of the search form, this is important.

In the search form add this code

Dim whoCalled As String '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Public Sub New(caller As String)
    InitializeComponent()
    whoCalled = caller
End Sub

The variable whoCalled will contain the name of the caller.

If you want to make it impossible to create the form without passing the data, then in the search form also add

Private Sub New()
    ' This call is required by the designer.
    InitializeComponent()
End Sub

This will force you to use the overloaded constructor.

Upvotes: 2

Related Questions