Friday, March 4, 2011

How can I refer to a control within its event? (without using it's name)

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
From stackoverflow
  • Yes, the "sender" parameter is the control that triggered the event.

    Gishu : You'd need to cast it to the specific type e.g. RadioButton
  • You can choose the name of the event. You can do it with the Event windows (next to the Property Windows) or inside the code. You choose the name all the time. You can simply use "checkedEvent".

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

    Inside this method you can use sender object and CAST it to (CheckBox) and use it's property... and behavior...

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

    You can find a great article that will explain you all in VB.NET with a TextBox event (he has several textbox and only 1 method to handle them all:

    alt text

  • Lets see if I remember VB.NET:

    Dim rb as RadioButton = sender
    If rb.Checked Then...
    
  • 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
    

0 comments:

Post a Comment