0

I'm new to custom classes. I have a class called 'game'. In the class, I have a method called 'addGame()' that creates a dynamic picture box called 'pBox'. After creating the control, I'm doing the following to register a click event:

AddHandler pBox.Click, AddressOf Me.launchGame

And here is launchGame:

Public Sub launchGame()
    MsgBox(Me.name)
End Sub

The problem is, "Me.name" is always the most recently added instances name, not the one I clicked on.


Based on a suggestion, I also tried this:

Public Sub launchGame(ByVal sender As Object)
    MsgBox(sender.name)
End Sub

But now "AddHandler pBox.Click, AddressOf Me.launchGame" says

Method 'Public Sub launchGame(sender As Object)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As System.EventArgs)'

And "AddHandler pBox.Click, AddressOf Me.launchGame(Me)" says

AddressOf operand must be the name of a method without parentheses


Public Sub launchGame(ByVal sender As Object, ByVal sender as EventArgs)
    MsgBox(sender.name)
End Sub

Now no errors, but the msgBox is blank.

10
  • 1
    Have you tried adding a parameter ByVal sender as Object and then doing sender.name? Commented Nov 30, 2012 at 3:31
  • "AddressOf must be the name of a method without parentheses" and if I add ByVal sender to launchgame, then it wants me to pass an object. Catch 22 or something :) Commented Nov 30, 2012 at 3:36
  • 1
    I'm glad you did the edit! The first error is only saying that you also need to add ByVal e as System.EventArgs - just don't put anything after the Me.LaunchGame for the AddressOf Commented Nov 30, 2012 at 3:42
  • 1
    And pBox has a name, right? Or are you trying to get the name of the game class instance? Commented Nov 30, 2012 at 3:50
  • 2
    let us continue this discussion in chat Commented Nov 30, 2012 at 4:06

1 Answer 1

0

I think the problem was that pBox was always the most recent pictureBox control. I created a control Array based on Creating Control Arrays in Visual Basic .NET and Visual C# .NET (MSDN).

Now I do the AddHandler in the AddNewpBox() method of my pBoxArray class. I also created a list to handle the "game" class, as suggested by David Brunow. Then I'm setting the pictureBox "Tag" property to the index of the game in the "games" array.

So now my click handler looks like the following, and it seems to work great.

Public Sub pBoxClick(ByVal sender As Object, e As EventArgs)
    MsgBox(games(sender.tag).name)
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.