AddHandler event on dynamic button, incorrect inst

2019-09-11 21:12发布

问题:

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.

回答1:

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