Reputation: 973
I have two objects, A and B, and both object have the same method called Hi. So A.hi will show a messagebox saying "hi I'm A" and B.hi will show a message saying "hi I'm B". They also both have a button that will activate this method.
How do I handle both these events in the same handler?
For example if I did them seperately, I would have this for A.
Private Sub btnHi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHiClassA.Click
A.hi
End Sub
I want to handle both events in same handler and I was able to do a tedious version with this logic;
Private Sub btnHi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHiClassA.Click, btnHiClassB.Click
if sender is btnHiClassA then
A.hi
elseif sender is btnHiClassB then
B.hi
end if
End Sub
Ideally it would go something like this:
Private Sub btnHi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHiClassA.Click, btnHiClassB.Click
'theObject = sender
'theObject.hi
End Sub
How would I do this?
Upvotes: 0
Views: 80
Reputation: 636
I would use Ctype. Ctype gets an object reference (like the sender) and converts it to a object, like a button. In this way you can get properties of the sender - dynamically. So if you have an Event Handler you can use as many objects to handle as you want.
Private Sub ButtonHi(sender As System.Object, e As System.EventArgs)
Dim ButtonName As String = CType(sender, Button).Name
If ButtonName = "ButtonHiA" Then
Msgbox("Hello World, I'm button A!")
ElseIf ButtonName = "ButtonHiB" Then
Msgbox("Hello World, I'm button B!")
End If
End Sub
As you may see, that sub is no real handler, therefore we must direct an object to it: This you can achieve in different ways, following are two.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
AddHandler ButtonHiA.Click, AddressOf ButtonHi
AddHandler ButtonHiB.Click, AddressOf ButtonHi
End Sub
Private Sub ButtonHiA_Click(sender As System.Object, e As System.EventArgs) Handles ButtonHiA.Click
ButtonHi(sender, e)
End Sub
Private Sub ButtonHiB_Click(sender As System.Object, e As System.EventArgs) Handles ButtonHiB.Click
ButtonHi(sender, e)
End Sub
If this is not what you're after, please clarify it in a comment beneath.
Upvotes: 0
Reputation: 11893
Define an interface IHiSender with the method Hi.
Implement IHiSender in all your classes.
Define a sub-class of EventArgs as HiSenderEventArgs with an additional property WhoAmI as type IHiSender.
Upvotes: 1