VB.Net通过循环创建事件时出现重复。

huangapple go评论59阅读模式
英文:

VB.Net Make Event through loop was duplicated

问题

我有一个代码片段展示了如何创建一个事件列表

在上面的代码中一切都正常但有一个问题是`MessageBox.Show`总是在while循环的最后显示一个固定的值

我找不出它是如何工作的你能帮助我吗
英文:

I have a snip code to show how a list of events was created.

While tb.MoveNext()
    Try
        idMenu = tb.Current.Field(Of Integer)("idMenu")
        menuName = tb.Current.Field(Of String)("HeaderName")
        ClassType = tb.Current?.Field(Of String)("ClassType")
        newTreeItem = New TreeViewItem()

        Dim clickHandler As New MouseButtonEventHandler(Sub(sender, e)
                                                            MessageBox.Show(menuName)
                                                        End Sub)
        AddHandler TryCast(newTreeItem, TreeViewItem).PreviewMouseDoubleClick, clickHandler
     Catch ex As Exception

     End Try
End While

In the above code, anything working ok but have a problem is MessageBox.Show always shows a fixed value at the last of the while loop.

I can't find out how it works. Can you help me with that!

答案1

得分: 2

我认为你遇到了一个问题,这是因为你的 Message 在以下代码行中的设置方式:

> Sub(sender, e)
> MessageBox.Show(menuName)
> End Sub

变量 menuName 不是事件处理程序代码的一部分。

你可以尝试这样做:

Sub(sender, e)
    Dim localMenuName as String = tb.Current.Field(Of String)("HeaderName")
    MessageBox.Show(localMenuName)
End Sub
英文:

I think you are encountering a problem because of how your Message is setup in the line:

> Sub(sender, e)
> MessageBox.Show(menuName)
> End Sub

The variable menuName is not part of the EventHandler code.

You could try this:

Sub(sender, e)
    Dim localMenuName as String = tb.Current.Field(Of String)("HeaderName")
    MessageBox.Show(localMenuName)
End Sub

huangapple
  • 本文由 发表于 2023年6月16日 00:05:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定