Search code examples
vb.neteventsaddhandler

VB.Net Make Event through loop was duplicated


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!


Solution

  • 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