sender

ADO DOT NET

Centurion
Joined
Dec 20, 2006
Messages
160
Visual Basic:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
---
If I call it as follows in form load:
Visual Basic:
CheckBox1_CheckedChanged(Me, Nothin)
Then sender.ToString will be: Project_Name.ProjectName.FormName

But if user manually click on the check box then sender.ToString will be: System.Windows.Forms.CheckBox, CheckState: 1/0

Now I want to do some thing if user clicked on the check box and do some thing if it was called on form load event.

I can do it this way:
In CheckBox1_CheckedChanged event I use sender.ToString and compare this string, to see how this event has been called!

But this does seem to be logical.
There should be a better way.
 
Last edited by a moderator:
You could alternatively check the sender's type or cast it to a control and check it's name.

If you want it to do two different things based on how it is called it might be easier to either handle the form load and the check changed event's with their own event handlers.
 
You can use VB's TypeOf ... Is operator, like so:
Code:
[Color=Blue]If TypeOf[/Color] sender [Color=Blue]Is[/Color] Form [Color=Blue]Then
[/Color]    [Color=Green]' Do things and stuff[/Color]
[Color=Blue]Else If TypeOf[/Color] sender [Color=blue]Is[/Color] CheckBox [Color=Blue]Then[/Color]
    [Color=Green]' Do other things and stuff[/Color]
[Color=Blue]End If[/Color]
I personally would just do a simple object comparison such as:
Code:
[Color=Blue]If[/Color] sender [Color=Blue]Is Me Then
[/Color]    [Color=Green]' Do things and stuff[/Color]
[Color=Blue]Else If[/Color] sender[Color=Blue] Is [/Color]CheckBox1 [Color=Blue]Then[/Color]
    [Color=Green]' Do other things and stuff[/Color]
[Color=Blue]End If[/Color]
 
Back
Top