Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET What is Sender used for?

Tags:

vb.net

sender

I'm confused as to the purpose of the sender parameter in Winform controls, for example:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

End Sub

I understand i can verify what sender holds by doing something as so:

If TypeOf sender Is Label Then
 'Execute some code...
End If

But is there a good reason that sender is included in every single control when it generates the sub-routine for me? In other words, i double click on a Form and i get the Private Sub form_load (sender....) and e As System.EventArgs.

What are some common usage of these two parameters? Are they always required?

Thank you,

Dayan D.

like image 571
Dayan Avatar asked Jul 29 '12 21:07

Dayan


People also ask

What is sender in VB net?

The sender parameter will reveal which Textbox was clicked. Private Sub FindIt( ByVal sender As System.Object, ByVal e As System.EventArgs. ) Handles TextBox1.

What is sender and EventArgs?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

What is sender As object E as EventArgs in VB net?

Sender is the object that raised the event and e contains the data of the event. All events in . NET contain such arguments. EventArgs is the base class of all event arguments and doesn't say much about the event.

What is the use of object sender in C#?

In the general object, the sender is one of the parameters in the C# language, and also, it is used to create the instance of the object, which is raised by the specific events on the application. That event is handled using the Eventhandler mechanism that is mostly handled and responsible for creating the objects.


1 Answers

sender contains the sender of the event, so if you had one method bound to multiple controls, you can distinguish them.

For example, if you had ten buttons and wanted to change their text to "You clicked me!" when you clicked one of them, you could use one separate handler for each one using a different button name each time, but it would be much better to handle all of them at once:

Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click
    DirectCast(sender, Button).Text = "You clicked me!"
End Sub
like image 180
Ry- Avatar answered Sep 19 '22 23:09

Ry-