参数化子的处理程序

时间:2014-06-27 17:45:17

标签: vb.net

我的WinForm上有十个图像,我试图在一个Sub中处理十个图像中的任何一个。 图像具有以下命名lblPlayer1,lblPlayer2等 我想要做的是为点击的任何图像调用click事件。

Private Sub lblPlayer1_Click(sender As Object, e As EventArgs) Handles lblPlayer(X).Click

End Sub

有可能吗?

2 个答案:

答案 0 :(得分:1)

Private Sub lblPlayers_Click(Byval sender As Object,Byval e As EventArgs) Handles 
lblPlayer1.Click,
lblPlayer2.Click,
lblPlayer3.Click,
etc...

End Sub

否则:

SomeSub() handles mybase.load

  For each ctrl as control in {lblPlayer1, lblPlayer2, lblPlayer3, etc...}
      addhandler ctrl.click, adressof lblPlayers_Click
  Next ctrl

End Sub

Private Sub lblPlayers_Click(Byval sender As Object,Byval e As EventArgs)
 ' Stuff Here...
End Sub

答案 1 :(得分:1)

Handles clause可以采用以逗号分隔的事件列表,因此您可以执行以下操作:

Private Sub lblPlayer1_Click(sender As Object, e As EventArgs) Handles lblPlayer1.Click, lblPlayer2.Click, lblPlayer3.Click, lblPlayer4.Click, lblPlayer5.Click, lblPlayer6.Click, lblPlayer7.Click, lblPlayer8.Click, lblPlayer9.Click, lblPlayer10.Click

End Sub

这将开始变得有点笨拙。您还可以使用AddHandler为表单构造函数或表单加载事件中的每个标签添加处理程序。