Results 1 to 4 of 4

Thread: [RESOLVED] Multi-Button - one procedure

  1. #1

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    45

    Resolved [RESOLVED] Multi-Button - one procedure

    I have a system with 26 buttons but the buttons actaully run the same code; aside from the fact that the index number is used to distinguish between them (es, I know index values are out so I am using the object's name (btnKey1, btnKey2, etc).

    Is there any event that occurs for all button presses or do I need to write the same line for all 26 events (actually 52 since I am using MouseDown and MouseUp - will get worse when I want to use the keypress side)?

  2. #2
    Addicted Member
    Join Date
    Jan 2012
    Location
    Athens, Greece
    Posts
    143

    Re: Multi-Button - one procedure

    You can use the same handler for all buttons using Handles after the sub definition.

    You can identify the button with the sender parameter of the sub.

    VB.Net Code:
    1. Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
    2.         Try
    3.             MsgBox(TryCast(sender, Button).Name)
    4.         Catch ex As Exception
    5.             MsgBox(ex.Message)
    6.         End Try
    7. End Sub

  3. #3
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Multi-Button - one procedure

    You can do it in the Designer by selecting all the buttons e.g. with shift-click. Make sure you select only the buttons, not the form for example. Then click the lightning icon at the top of the Properties window and select the Click event. A single Click event handler for all the selected buttons will appear in the code. It will have a Handles clause like this:
    Code:
    Handles btnKey1.Click, btnKey2.Click, btnKey3.Click '... and so on
    Then you can use the Sender argument of the handler sub to decide which of the buttons was clicked.

    There's another way if you want to do it all in code instead of in the designer. Please say if you want to know about that.

    BB

    EDIT: I just saw pkarvou's answer and we agree about this method.

  4. #4

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    45

    Re: Multi-Button - one procedure

    "And I love you so,
    The people ask me how
    How I've lived 'till now
    I tell them I don't know!"

    Thanks so much!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width