Results 1 to 16 of 16

Thread: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2006
    Posts
    176

    What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    Hi All
    I just don't get what the () after the sub name does...kind of stupid
    question, but it would be nice to understand it. What is each parameter?
    Thanks.

  2. #2
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,710

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    Its the signature of the event. The sender is the object that the event is being raised upon. So if you have a event with several handles objects you can determine which object was invoked.

    Take a signature like this.
    Code:
    Public Class Form1
    
    	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
    		Dim oButton As Button = DirectCast(sender, Button)
    		MessageBox.Show(oButton.Text & " was clicked")
    	End Sub
    
    End Class
    Now the e parameter is additional info about the event being raised.

    Take this event for example:
    You can easily determine what the reason is that the form is being closed.
    Code:
    Public Class Form1
    
    	Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    		Select Case e.CloseReason
    			Case CloseReason.ApplicationExitCall
    				'
    			Case CloseReason.FormOwnerClosing
    				'
    			Case CloseReason.MdiFormClosing
    				'
    			Case CloseReason.None
    				'
    			Case CloseReason.TaskManagerClosing
    				'
    			Case CloseReason.UserClosing
    				'
    			Case CloseReason.WindowsShutDown
    				'
    		End Select
    	End Sub
    
    End Class
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    A few further points:

    1) It is quite likely that you would use neither of these. They are there for convenience, so that the sub has that information if needed, but you certainly don't HAVE to do anything with them.

    2) EventArgs is kind of a catch all class. Many subs derive from this base, but since a derived class can be cast to its base, this would allow you to pass a more specific set of args which have been derived from EventArgs, then in the sub you can cast it back to the correct type. Of course, you'd have to know what the correct type is, but if you designed the thing, then you'd know that.
    My usual boring signature: Nothing

  4. #4
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,710

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    There is soo much to this topic though that we can not cover all bases.

    For example you could also derive your own EventArgs class to pass custom arguments to your event.

    The posibilities are fun to explore.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    Here's an example of how you might create a class that raised a couple of events that demonstrates how that signature is used:
    vb.net Code:
    1. Public Class Thing
    2.  
    3.     Private _data As String
    4.  
    5.     Public Property Data() As String
    6.         Get
    7.             Return Me._data
    8.         End Get
    9.         Set(ByVal value As String)
    10.             If Me._data <> value Then
    11.                 Dim e As New CancelEventArgs
    12.                
    13.                 'The value of the property is changing so raise the DataChanging event.
    14.                 Me.OnDataChanging(e)
    15.  
    16.                 If Not e.Cancel Then
    17.                     'The property change has not been cancelled so change the property value.
    18.                     Me._data = value
    19.  
    20.                     'The property value has changed so raise the DataChanged event.
    21.                     Me.OnDataChanged(EventArgs.Empty)
    22.                 End If
    23.             End If
    24.         End Set
    25.     End Property
    26.  
    27.     Public Event OnDataChanging As EventHandler(Of CancelEventArgs)
    28.     Public Event OnDataChanged As EventHandler
    29.  
    30.     Protected Overridable Sub OnDataChanging(ByVal e As CancelEventArgs)
    31.         RaiseEvent DataChanging(Me, e)
    32.     End Sub
    33.  
    34.     Protected Overridable Sub OnDataChanged(ByVal e As EventArgs)
    35.         RaiseEvent DataChanged(Me, e)
    36.     End Sub
    37.  
    38. End Class
    See how in both cases the events are raised with two parameters. The first is 'Me', so it is the object raising the event. That is what gets received via the 'sender' parameter in a handler for that event. The second is an EventArgs object or an object of a type derived from EventArgs, e.g. CancelEventArgs. That is what gets received via the 'e' parameter.

    If you need to provide data to, or get data from, the handlers for an event then you use a type derived from EventArgs. In this case the event can be cancelled, so a CancelEventArgs is used. In the event handler the e.Cancel property can be set to True to cancel the event.

    Notice in the setter for the Data property, when the property value is changing a CancelEventArgs object is created and passed to the OnDataChanging method. That method then raises the DataChanging event. All handlers for that event then get a chance to set e.Cancel to True. In the Data property the value of e.Cancel is then tested. Only if it is False is the property value actually changed.

    Once the property value is changed the DataChanged event is raised. Note that in that case EventArgs.Empty is passed to the OnDataChanged method. For events that don't actually require any data you always use EventArgs.Empty. An EventArgs object never contains any useful data.

    Whenever you raise events in your own classes you should ALWAYS follow this pattern. You don't actually have to but you always should for consistency.

  6. #6
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    [QUOTE=RobDog888;3093598][color=navy]Its the signature of the event. The sender is the object that the event is being raised upon. So if you have a event with several handles objects you can determine which object was invoked.

    Though i get this answer now, but as a matter of fact, I found your reply so helpful Rob.

    but there is a thing which is passing over my head i.e.
    Its the signature of the event. The sender is the object that the event is being raised upon.
    Would you please show me that what does it mean?

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    [QUOTE=ADQUSIT;4402251]
    Quote Originally Posted by RobDog888 View Post
    [color=navy]Its the signature of the event. The sender is the object that the event is being raised upon. So if you have a event with several handles objects you can determine which object was invoked.

    Though i get this answer now, but as a matter of fact, I found your reply so helpful Rob.

    but there is a thing which is passing over my head i.e.

    Would you please show me that what does it mean?
    Rob's example from post #2 shows exactly what it means and my example from post #5 shows exactly how it works.

  8. #8
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    I'm sorry to say, that i did not understand that exact meaning of his wordings. I tried to compare the code with his idea, but couldn't pick it. Please guide me that what is sender as System.Object meaning?

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    Sender is the object that raised the event. Therefore, if the event is a button click, then sender will be the button that was clicked. Of course, it couldn't be written as: Sender As Button, because that would ONLY work for buttons, which would mean that you could ONLY use buttons for that kind of an event. To allow people to have a single handler method handle a variety of events, sender has to be sufficiently generic that it could be any of the objects that might raise that event. For example, a Button is not the only thing that has a Click event you can use. I often use click events for panels, pictureboxes, and occasionally labels, but pretty nearly every control will raise a click event. If I want the same sub to handle click events from some buttons, some panels, and a picturebox, then sender can't be type button, as that would exclude the panels and the picturebox. Technically, sender could be type Control, as button, panel, and picturebox all derive from Control, but then sender would have to be a control, so that still limits the versatility. The only type sufficiently general is the common base of all types: Object. Therefore, sender is type Object. If you know what type it really is, such as button, then you cast it to button. If you know that it is a control, but you don't know which type (though you can ALWAYS find out what type, if you want to), then you could cast it to type Control.
    My usual boring signature: Nothing

  10. #10
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    very well done shaggy.

    Please explain the same way what is 'e' as system.eventArgs means?

  11. #11
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    ADQUIST, I glanced at a few of your past posts and so I know you know how to use e in this situation:

    vb.net Code:
    1. Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    2. End Sub

    in this case e gives you access to all the event arguments of the KeyPress Event... In the Intelliprompt it shows you Two choices under Common:

    • e.Handled
    • e.KeyChar



    However if you go over to all, you also see:

    • Empty
    • Equals
    • GetHashCode
    • GetType
    • ReferenceEquals
    • ToString



    Now if we look at:

    vb.net Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2. End Sub

    what is e used for? not much. lets look at the Intelliprompt again:

    • Empty
    • Equals
    • GetHashCode
    • GetType
    • ReferenceEquals
    • ToString


    Look familiar?

    Forgive me if I'm using incorrect terminology here, but basically e as System.EventArgs is the general catch-all event argument handler. Where as in the Keypress event e is modified for the keypress event. As VB.Net evolves, more and more you will see common ancestry like this for the sake of code clarity and ease of understanding... think about it, any time you create an event, all you have to do is type "e." and a prompt will appear with all of your useful event arguments.

    I hope that helps clarify for you.

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  12. #12

  13. #13
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,748

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  14. #14
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    That's alright. Looking back, that was one of my worst explanations yet. Let me give it another crack. I'm going to put a few more details in this one, so please ask specific questions if you're still confused.

    Lets start with the basics.

    VB.net is object oriented programming. That means that everything and anything in the program, big or small, either is, or can be thought of as an object. This is really simple when you think of controls like buttons and Labels, they're objects. What's more difficult is realizing that ideas are objects also. a variable is an object. anything can be thought of this way. Let's say for example that we have a DOG as our object.

    There are a few things that are associated with all objects. Events and Properties. or in other words:

    Brown Dog <- Describing the dog, Property
    Dog Jumps <- What the dog does, Event

    In your code, this would look something like:

    Code:
    Dog.Color = Colors.Brown
    
    Sub Dog_Jump(blablabla) Handles Dog.Jump
    'insert code here
    End Sub
    Just as Shaggy Hiker was mentioning earlier, controls are objects, and sometimes they share properties and events. The key here is to understand that when something is an object, you can do something with it, even if you don't know what type of object it is when you write your code. Lets look at the same example using some real objects. Lets use our Button and Label from earlier. They both have a 'text' property, and they can both be clicked. If we look at this code:

    Code:
    Private Sub Stuff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Label1.Click
        If TypeOf sender Is System.Windows.Forms.Label Then
            Label1.Text = "Label"
        ElseIf TypeOf sender Is System.Windows.Forms.Button Then
            Button1.Text = "Button"
        End If
    End Sub
    This is what Shaggy Hiker was describing earlier. Here's what we're doing here:

    We've created a sub, in this case an event. This event Handles the click event of both button1 and Label1, In other words, Whenever you click EITHER Button1, or Label1, This code is run. What Shaggy Hiker described to you earlier was the second part: You can share code between many items by using the sender to determine where you want to use the code. By figuring out what type of object the sender is, you can then manipulate it further. Before I go on, I want to clarify why this is important... What if you had 3 buttons and 3 labels, but you wanted to do the same thing to each when clicked... Instead of rewriting the same code 6 times you can write:

    Code:
    Private Sub Stuff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Label1.Click, Label2.Click, Label3.Click
        If TypeOf sender Is System.Windows.Forms.Label Then
            Dim TempLabel As Label = sender
            TempLabel.Text = "Label"
        ElseIf TypeOf sender Is System.Windows.Forms.Button Then
            Dim TempButton As Button = sender
            TempButton.Text = "Button"
        End If
    End Sub
    This is a bit more complicated, but much shorter than writing 6 different subroutines, especially if there were more code than this. The only thing different here that I've done is I've created a temporary Label and assigned it to the sender This allows me to write code specific to a Label, even though I don't know if its a label yet. That's why I have the If statement first. There are other ways to do this, but this is the most clear.

    I know you said you were already clear on the sender, but this example allows you to look at the structure of the sub, rather than just the sender. Now I can explain e and it will be a bit more clear.

    e is your event arguments. it is an object. think of the keypress event:

    Code:
    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
        Label1.Text = e.KeyChar.ToString
    End Sub
    *note if this code doesn't work for you, keep in mind that your form may not be in focus. If you have a button on the form, generally it will take the focus, and any keypresses would raise the button.keypress event instead*

    In this example e is the KeyPress Event Arguments... this is a specific TYPE of (Event Argument). If you think of (Event Argument) as (Object) this starts to look familiar... this is a specific TYPE of (OBJECT)

    So, just like how I reassigned the label in code, I can do the same thing to e:

    Code:
    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.KeyPress
        Dim KeypressArgs As System.Windows.Forms.KeyPressEventArgs = e
        Label1.Text = KeypressArgs.KeyChar.ToString
    End Sub
    Just as Object is the base of all our senders, System.EventArgs is the base of all our Event Arguments. You can even simplify this further:

    Code:
    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As Object) Handles Me.KeyPress
        Dim KeypressArgs As System.Windows.Forms.KeyPressEventArgs = e
        Label1.Text = KeypressArgs.KeyChar.ToString
    End Sub
    EVERYTHING IS AN OBJECT

    Now imagine if I wanted to do the same exact thing wether you click an OK button, or Hit enter in a textbox... This is a pretty common thing to do. I could do it this way: *Note: Not the best way to do it*

    Code:
        Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
            DoSomethingSub()
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            DoSomethingSub()
        End Sub
    
        Private Sub DoSomethingSub()
            'do something here
        End Sub
    Or you could create your own:

    Code:
        Private Sub DoSomethingElse(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, TextBox1.KeyDown
            If TypeOf sender Is TextBox Or TypeOf sender Is Button Then
                If TypeOf sender Is TextBox Then
                    Dim KeydownArgs As System.Windows.Forms.KeyEventArgs = e
                    If KeydownArgs.KeyCode <> Keys.Enter Then
                        Exit Sub
                    End If
                End If
                'DoStuffHere
            End If
        End Sub
    Here you're raising the sub from two different types of events... You don't know what type of event happened, so you don't know if you need to check the keycode, or just do the stuff anyways. You use the sender to figure out what type of object called it, and then use the event arguments to determine the key.

    I hope this help you further, if not please ask specific questions on what part you don't understand.

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  15. #15
    Fanatic Member
    Join Date
    Nov 2010
    Posts
    965

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    This is adorable link dbasnett.

    Its classical. I got so many things from this, but would you please guide me for one thing. It is written there that:
    An event sender pushes a notification that an event has happened, and an event receiver receives that notification and defines a response to it.
    Where the sender sends the notification? and from where the receiver receives the notification?
    I mean that is it some type of checking/ matching procedure behind it? if yes? there where it is matched or checked?

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: What does (ByVal sender As System.Object, ByVal e As System.EventArgs) mean?

    No, not really. Think of it this way:

    Any object can raise an event. Most don't, but some, including all controls, do. Whenever some specific thing happens, such as a button click, the object (the button, in this case) raises the event. So, what does that mean? Well, you can create a class with an event like so:

    Code:
    Public Foo
     Public Event SomeEvent()
    
     Public Sub ImAMethod()
      RaiseEvent SomeEvent
     End Sub
    End Class
    That's not the best way to do it, but it works. The class declares an event, then when the method is called, the class raises the event. So, what is happening? What is happening behind the scenes is that when the class has the line Public Event SomeEvent, it is creating a list of methods. There is nothing in this list, so it is an empty list, but the list exists. Now, over in some form or other object, you can add a handler for SomeEvent using either the Handles clause or AddHandler. Either way, you are adding a method, because the Handles clause is always attached to a Sub, and AddHandler requires the address of a Sub as one of its arguments. What the compiler does is that it gives the address of the Sub to the object that has the event (Foo in this case) and tells it to add the Sub to the list created with the Public Event SomeEvent line. You don't really interact with Foo at all for this in VB (though you do somewhat in C#), since it is all done by the compiler, but the real result of the Handles clause or AddHandler is that the Sub in question is given to the object that will raise the event so that the object can add the address of that Sub to the list it is maintaining for the event.

    Later on, when the RaiseEvent method is reached, all the object does is go through the list calling each Sub in turn. There may be nothing in the list if no other object is handling the event, but that doesn't matter at all. If the list is empty, then RaiseEvent doesn't do anything at all. If the list has one Sub in it, then it calls that one Sub. If the list has multiple Subs, then it calls each one of those Subs.

    That's pretty much how the event model works.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width