tags:

views:

166

answers:

4

Is there a way in .net to refer to a control generically (so that if the control name changes, etc.) you don't have a problem.

I.e., the object level version of the "me" keyword.

So, I'd 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
+8  A: 

Yes, the "sender" parameter is the control that triggered the event.

bobwienholt
You'd need to cast it to the specific type e.g. RadioButton
Gishu
+2  A: 
Daok
+3  A: 

Lets see if I remember VB.NET:

Dim rb as RadioButton = sender
If rb.Checked Then...
Cristian Libardo
+2  A: 

If you just have the one control that triggers the event handler then there is little reason to generalize the code so you don't have to reference the actual name of the button. The compilation will break if the control doesn't exist.

However, if you have several controls hooked on to the same event handler then you should use the first argument (sender) that is passed to the handler. Now you can do something generic to any of the controls that triggered 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
thoughtcrimes