0

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!

djv
  • 15,168
  • 7
  • 48
  • 72
DevGold
  • 39
  • 1
  • 4
  • Why are you storing elsewhere `newTreeItem` & Co.? These Fields(?) of course store the last item generated in the loop. Have you checked what `sender` is when the event is raised? Why `.TryCast()`? Why not simply in-line the handler in `AddHandler`? – Jimi Jun 15 '23 at 16:38

1 Answers1

2

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
JayV
  • 3,238
  • 2
  • 9
  • 14
  • Your suggestion helps me clearly! I try to put a declaration Dim into a loop and it works. While tb.MoveNext() Dim localMenuName as String = tb.Current.Field(Of String)("HeaderName") '''' Call to event ''' End While – DevGold Jun 15 '23 at 21:52
  • @DevGold Glad to read it works for you. Please don't forget to mark the answer as accepted. – JayV Jun 15 '23 at 21:59