locked
determine specific control RRS feed

  • Question

  • I'd like to have the same event be used for several controls. For example, if I have 3 buttons I'd like the click event of one of the buttons be used when any of the  3 buttons  are selected ...

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click, Button4.Click, Button3.Click

    Within this subroutine how do I use sender to determine which button was clicked?

    End Sub

     

     

    Friday, September 29, 2006 7:12 PM

Answers

  • The following will determine which control was clicked and display it in a label.

     

     

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click

    Label1.Text = CType(sender, Control).Name

    End Sub

    Friday, September 29, 2006 7:25 PM

All replies

  • The following will determine which control was clicked and display it in a label.

     

     

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click

    Label1.Text = CType(sender, Control).Name

    End Sub

    Friday, September 29, 2006 7:25 PM
  • Since sender is an object, you'd have to convert t to the correct 'type' (i.e. a button) and you can then query the properties of it:

    Dim b As Button = TryCast(sender, Button)
    If b Is Nothing Then
        ' a button didn't raise this event!
        Return
    End If
    Debug.WriteLine(b.Name)

     

    Friday, September 29, 2006 7:28 PM
  • This would work if you knew that only button events where hooked up but as we can now hook up different controls events to a method - I had used the ctype to control - just to get the name to demonstrate getting the control that fired the method.

    If you want to do something with it then you would probably cast it to the specific type required to get intellisense etc.

     

     

    Friday, September 29, 2006 8:45 PM