【问题标题】:Visual basic 2008 issue with adding a method to my dynamic objects向我的动态对象添加方法的 Visual Basic 2008 问题
【发布时间】:2013-05-08 00:51:57
【问题描述】:

自上周四以来,我一直在寻找问题的答案。 vb.net 已经回答了很多关于我完全相同的问题的答案。但是,我正在使用 Visual Basic 2008,这两种语言似乎有我难以理解的差异。所以这是我的问题。

我需要创建几个图片框,并且我已经按照几个网站的推荐动态创建了它们。那部分工作正常。当我想点击它们时,问题就开始了。我读得足够明白,这不是因为我创建了对象,而是创建了附加到它们的方法。然后我创建方法。仍然没有问题,除非我在运行代码时每个按钮都执行相同的操作,因为它们都附加到相同的方法。我找到了一个解决方案:我需要用方法传递一个参数来告诉我正在点击的图片框,但是因为我使用的是 addressof 我不能。我知道很少有网站讨论过相同的问题并使用 lamda 表达式解决了它。如果有人能给我我应该使用的代码,我将非常感激。

这是我的代码:

For i = 0 To 7
     'couleur is the name I give to my picturebox object and objet () is the sub in   which    I  created my object
    couleur(i) = objet()
Next

For x = 0 To 7
   ' initiasation of location, etc.
Next


   '     This is the issue !!! I do not know how to say this line into vb8
   ' I want to pass in argument  X to know on which object I have cliked on and then use a seled case to make separated command afterward.  
For x = 0 To 7
      AddHandler couleur(i).Click, Function(senderobj, args) couleur_click(x)
Next


End Sub

Sub couleur_click(ByVal i As Integer)

' select case doing seperated things depending on the x receive in argument

End Sub

感谢大家的帮助,抱歉我的语言不是我的母语。

【问题讨论】:

    标签: vb.net lambda expression addhandler addressof


    【解决方案1】:

    为什么不把couleur_click改成把sender作为参数呢?然后您将知道点击的来源,您可以从中找到PictureBox 在您的couleur 数组中的索引:

    ' ...
    For x = 0 To 7
          AddHandler couleur(i).Click, AddressOf couleur_click
    Next
    ' ...
    
    Sub couleur_click(sender As Object, e As EventArgs)
       Dim pictureBoxSource As PictureBox = sender
    
       ' Find the index of the source in the base collection
       Dim index = Array.IndexOf(couleur, pictureBoxSource)
    
        Select Case index
            ' ...
        End Select
    End Sub
    

    【讨论】:

      【解决方案2】:

      设置每个 PictureBox 的 tag 属性,然后在 click 事件处理程序中你可以对 tag 做一个 select case。

      您不能将参数添加到内置事件处理程序。

      【讨论】:

      • 我是新手,我刚刚所做的研究现在让我明白了我必须如何使用标签来解决我的问题。你能解释一下标签是什么以及我必须如何在我的情况下使用它吗?谢谢你的帮助
      • @PascalLevesque,他的意思是PictureBox 类有一个Tag 属性,您可以在其中放置索引整数。然后,您的事件处理程序可以从标记中提取整数,假设您可以访问 sender,如我的示例所示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多