Home > Enterprise >  VB.net - How to send multiple senders to event handler
VB.net - How to send multiple senders to event handler

Time:07-23

I have MonthlyCalendar created and shown once a text box is clicked "e.g. Date of Birth". I do have multiple dates text boxes in my Form and I would like to send the actual text box as Object "clicked" along with the MonthlyCalendar as Sender as well , 3 arguments.

Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles txtDOB.Click
        Dim mc = New MonthCalendar()
        AddHandler mc.DateSelected, AddressOf DateSelected
        Me.Controls.Add(mc)
        mc.BringToFront()
        mc.Show()
End Sub

 Private Sub DateSelected(sender As Object, e As DateRangeEventArgs) Handles MonthCalendar1.DateSelected
        txtDOB.Text = DirectCast(sender, MonthCalendar).SelectionRange.Start.Date.ToString("yyyyMMdd")
    End Sub

I would like the handler to be like this:

1st argument the actual textbox clicked 2nd argument the Monthly Calendar 3rd argument the DateRangeEventArgs

AddHandler mc.DateSelected, AddressOf DateSelected(sender 'Textbox as Object, sender 'MontlyCalendar As Object, e As DateRangeEventArgs)

Appreciate guidance and a better way of doing this

CodePudding user response:

You don't send anything to an event handler. The object itself raises the event in response to something done to it and it sends the arguments to the event handler. You can't change the signature and you can't choose what arguments it receives.

Probably your best bet would be to, when you create the MonthCalendar, assign the corresponding TextBox to its Tag property.

Dim mc = New MonthCalendar With {.Tag = sender}

Tag is a general-purpose data property of type Object, so there's no need to cast sender at this point. You know that the actual object is a TextBox, because that's all that will raise that event.

In the event handler, you can then get the MonthCalendar from the sender and the TextBox from its Tag.

Dim mc = DirectCast(sender, MonthCalendar)
Dim tb = DirectCast(mc.Tag, TextBox)
  • Related