Very wierd behaviour with Treeview Control

Arokh

Centurion
Joined
Apr 11, 2006
Messages
124
Hi

I'm having trouble with the TreeView Control:
I sometimes want to add nodes or edit them but it seems to do both sometimes
which of course messes up its content.

What is really odd:
This only happens when the Treeview is visible.
If I place it on a TabControl, on a Tab which is not viewed it works exactly as I want it to,
but as soon as I switch to the tab which contains the Treeview, it messes up again.

First I thought something is wrong with my code but I reduced the code to the base problem but it still happens:
Visual Basic:
Public Class Form1
    Delegate Sub CrossThread(ByVal J As Integer)
    Dim ItemAdder As New Threading.Thread(AddressOf ItemAdd)

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ItemAdder.Start()
    End Sub

    Private Sub ItemAdd()
        For J As Integer = 0 To 100
            For I As Integer = 0 To 1
                AddNode(J)
                Threading.Thread.Sleep(500)
            Next
            Threading.Thread.Sleep(500)
        Next
    End Sub

    Private Sub AddNode(ByVal J As Integer)
        With TreeView1
            If .InvokeRequired Then
                Dim AddNodeSub As CrossThread = AddressOf AddNode
                .Invoke(AddNodeSub, J)
                Exit Sub
            End If

            If .Nodes.Count - 1 < J Then
                .Nodes.Add(New TreeNode(J & " BlaBla"))
            Else
                Dim Node As New TreeNode(J & " BlaBla")
                Node.Nodes.Add(New TreeNode("SubNode1"))
                Node.Nodes.Add(New TreeNode("SubNode2"))
                .Nodes(J) = Node
            End If
        End With
    End Sub
End Class

I've also attached the Project.
Start it up wait some seconds and switch to the second tab,
everything is correct until then but as the next nodes are added it messes up.
If you restart it again and immediately switch to the second tab, it messes up from the beginning.
 

Attachments

Try calling TreeView.BeginUpdate() before you begin modifying the TreeView and calling TreeView.EndUpdate() when you are done.
 
Back
Top