AddHandler event on dynamic button, incorrect instance properties in VB.NET

拟墨画扇 提交于 2019-12-12 05:27: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


来源:https://stackoverflow.com/questions/13638582/addhandler-event-on-dynamic-button-incorrect-instance-properties-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!