Results 1 to 2 of 2

Thread: Is there a better way of doing this?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jun 2011
    Posts
    17

    Is there a better way of doing this?

    Hey

    I have a button array that I filled up. Here is the code I used to do that.
    Code:
    Public buttons(29) As Button
    Code:
    For i = 0 To 29
          buttons(i) = CType(Me.Controls("Button" & i), Button)
          i += 1
    Next i
    Here is some code that I used (it is extremely inefficient):
    Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button15.Click, Button16.Click, Button17.Click, Button18.Click, Button19.Click, Button20.Click, Button21.Click, Button22.Click, Button23.Click, Button24.Click, Button25.Click, Button26.Click, Button27.Click, Button28.Click, Button29.Click, Button30.Click
    Is there a better way of doing this? If so, how?

    Thanks,
    Faxmunky
    Last edited by faxmunky; Aug 10th, 2011 at 05:13 AM.

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

    Re: Is there a better way of doing this?

    That doesn't do anything yet, so it can't be inefficient in the usual sense. Are you looking for an alternative to typing all those button names by hand? If so, I can think of 3 ways:

    1. If you already have the buttons laid out on a form, Shift-Select them all. Go to the Properties window and click on the lightning-icon to get a list of events. Double click on the Click event in the list. The result will be like the code you posted.

    2. In code, you could use a loop with AddHandler to assign a sub to all the buttons. Search this forum for AddHandler for examples.

    3. Make your own version of the Button class. Select Project/Add Class ... in Visual Studio, give it a name (e.g. ButtonEx) and code the OnClick sub:
    Code:
    Public Class ButtonEx
    	Inherits Button
    
    	Protected Overrides Sub OnClick(e As System.EventArgs)
    
    		'put your button click code here
    
    		MyBase.OnClick(e)
    	End Sub
    
    End Class
    After you build the project, ButtonEx will appear in the toolbox with a cogwheel icon. In the Designer, you can drag these onto your form the same way as a normal buttons, but they will all have your special Click code.

    BB

    EDIT: I didn't see your edited post. You probably want method 2.

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