VB.NET What is a sender?

I am confused regarding 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 that I can check what sender does by doing something like this:

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

But is there a good reason that the sender is included in every control when it generates a routine for me? In other words, I double click on the form and get Private Sub form_load (sender....) and e As System.EventArg s.

What is the common use of these two parameters? Are they always needed?

Thanks,

Dayan D.

+7
source share
3 answers

sender contains the event sender, so if you have one method associated with several controls, you can distinguish between them.

For example, if you had ten buttons and you wanted to change your text to “You clicked me!” when you clicked on one of them, you could use one separate handler for each of them, each time using a different button name, but it would be better to process everything 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 
+15
source

e refers to the event arguments for the event used, they usually come in the form of properties / functions / methods that may be available on it.

In this example, the label text property will contain the BorderColor set for the footer style of our GridView when its FooterRow, defined from the string passed as the property of the event argument parameter, binds the data to this DataSource GridView.

 Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound If e.Row.RowType = DataControlRowType.Footer Then lblFooterColor.Text = e.Row.Style("BorderColor") End If End Sub 
+5
source

In the first half of the question:

sender used when a callback processes several events to find out which of the objects has blocked the event.

For example, instead of cutting and pasting the same code in two callback functions, you can have the same code that controls two different button press events:

 Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click Dim s As String If sender Is Button1 Then s = "button1" ElseIf sender Is Button2 Then s = "button2" End If MessageBox.Show("You pressed: " + s) End Sub 

Link here .

+1
source

All Articles