How can I refer to a control in its event? (without using his name)

Is there a way in .net to refer to a control in general (so if the name of the control changes, etc.), you have no problem.

Ie, the object level version of the keyword "me".

So, I would like to use something generic instead of RadioButton1 in the example below.

Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged

        If RadioButton1.Checked Then 
           Beep()

End Sub

      

0


source to share


4 answers


Let's see if I remember VB.NET:



Dim rb as RadioButton = sender
If rb.Checked Then...

      

+3


source


Yes, the sender parameter is the control that raised the event.



+8


source


You can choose the name of the event. You can do this with event windows (next to Property Windows) or inside code. You choose a name all the time. You can just use "checkedEvent".

this.checkbox.EventXYZ += new EventXZY(checkedEvent);

      

Inside this method, you can use the sender object and CAST it (CheckBox) and use its property ... and behavior ...

public ... checkedEvent(object sender,...)
    ((RadioButton)sender).....

      

You can find an article that will explain you everyone in VB.NET with the TextBox event (it has multiple text boxes and only 1 method to handle them:

alt text http://clip2net.com/clip/m12122/1228156822-clip-4kb.png

+2


source


If you only have one control that fires an event handler, then there is no reason to generalize the code, so you don't need to reference the actual button name. Compilation will fail if the control does not exist.

However, if you have multiple controls connected to the same event handler, you must use the first argument (sender) that is passed to the handler. Now you can do something general for any of the controls that raised the event:

Private Sub rbtn_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim rbtn As RadioButton = TryCast(sender, RadioButton)
    If rbtn IsNot Nothing Then
        If rbtn.Checked Then
            rbtn.Text = rbtn.Text & "(checked)"
        End If
    End If
End Sub

      

+2


source







All Articles