Populate TreeView in Background worker

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Developer111
    New Member
    • Apr 2010
    • 28

    Populate TreeView in Background worker

    In vb2005, I have to load a treeview control while loading the form so make the form loading more effective therefore I use Background worker to populate treeview. I tried treeview to pass by ref and faced the error “Cross thread operation not valid: Control” accessed from a thread other than the thread it was created on..”, which makes sense.
    Now I want to load treeview in background and return its object then assigning it : Is this the right mechanism?
    Can anybody give any idea about this?
    Thanks in Advance
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    Are you creating the TreeView object within the background worker, or within your form? If it's created within a seporate thread, id imagine you'll have no end of problems as i believe winforms needs everything within one thread.

    A solution is to create the worker yourself, heres a very simple example:

    Code:
    Public Class Form1
    
        Dim results As TreeNode
    
        Private Sub Button1_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles Button1.Click
    
            Dim myWorker As New Threading.Thread(AddressOf subA)
            myWorker.Start("noodle")
            While myWorker.IsAlive
                Application.DoEvents()
            End While
    
            If Not IsNothing(results) Then
                TreeView1.Nodes.Add(results)
            End If
    
        End Sub
    
        Sub subA(ByVal word As String)
            results = New TreeNode("Worked!")
            For i = 0 To 1000
                results.Nodes.Add(word)
            Next
        End Sub
    
    End Class
    Hope this helps :)


    Aimee.

    Comment

    • Developer111
      New Member
      • Apr 2010
      • 28

      #3
      This is usefull
      Thanks AmzBee... :)

      Comment

      Working...