Dean said:
When you drop a button on a form, a Click event is created by the
designer. Within the Click event certain event parameters are defined:
Private Sub btnInsert_ButtonPressed(ByVal sender As System.Object, ByVal
e As System.EventArgs)
What harm or limitations would ensue if (ByVal sender As System.Object,
ByVal e As System.EventArgs) were changed to ().
First guess - it wouldn't compile.
(actually VB'2008 might do some "clever" stuff; haven't got there yet)
VB wires up events using "delegates" and delegates are just methods with
a particular signature. If you don't supply the right arguments
(signature) for a method, VB can't wire up the event to that method (the
error is something like "method X cannot handle event Y").
I'm guessing that, like me, you're a VB "proper" Developer and I can see
what you're thinking - /why/ do you need these extraneous arguments?
Indeed, in the case you cite, there's not a lot of point but there's two
things to bear in mind:
(1) Other events /do/ use meaningful Event Argument classes, not just
the base class, EventArgs - take a look at, say, the Layout event; that
supplies your event handler with lots of useful stuff.
(2) Under VB "Proper" if you wrote six buttons, you'd get six *_Click
routines (ignoring Control Arrays). In VB.Net, you can have a /single/
method handling the click event of /many/ buttons, as in:
Private Sub AnyButton_Click( ... ) _
Handles btnInsert.Click _
, btn5_Click _
, btn10_Click _
, btn15_Click _
, ... and so on ...
So how does this routine know /which/ button you actually clicked on?
That's what "sender" argument is for - you get an object reference to
the control (here, a button) that raised the event, as in
Private Sub AnyButton_Click( ... ) _
Handles btnInsert.Click, ...
If ( TypeOf sender Is Button ) Then
MessageBox.Show( "You clicked " _
& DirectCast( sender, Button ).Name _
)
End If
End Sub
HTH,
Phill W.