Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

My backgroundworker reads from a txt file database and should put the data in a listview on the main form. Nothing came up in the listview, and I proved that data was going to it but was not written due to threading errors and such, but I don't know how to make it work.

-Rixterz
Posted

1 solution

You can't access UI elements except from the thread on which they were created: the UI thread. When you try, you get a cross thread exception - as you have seen.

Fortunately it's simple to fix: just Invoke[^] the control from the background worker, and it will move the execution onto the UI thread for you.
 
Share this answer
 
Comments
[no name] 14-Aug-14 7:16am    
Nope. I have this code:

Delegate Sub LoadPlayerListDelegate()
Private Sub ReadFromDatabase()
Dim Usernames As String = Nothing
Try
Dim r As New IO.StreamReader(My.Settings.DatabaseLocation)
Do While r.Peek() <> -1
Usernames &= r.ReadLine().Split(vbTab)(3) & "/"
Loop
r.Close()
If Form1.ListView2.InvokeRequired Then
Dim del As New LoadPlayerListDelegate(AddressOf ReadFromDatabase)
Form1.ListView2.Invoke(del)
Else
Form1.LoadPlayerList(Usernames)
End If
Me.Close()
Catch ex As Exception
If MessageBox.Show("Error: could not read from database." & vbNewLine & "Retry?", "Could not read from database", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
ReadFromDatabase()
Else
Application.Exit()
End If
End Try
End Sub
________________________
And on Form1, this:
________________________

Public Sub LoadPlayerList(Usernames As String)
MsgBox("Loadplayerlist here. usernames=" & Usernames) 'to make sure the sub is run
Me.Text = "huh" '<--- NOT WORKING - CROSSTHREADING ISSUES :C
For i As Integer = 0 To Usernames.Split("/").Count - 1
ListView2.Items.Add(Usernames.Split("/")(i))
Dim StatusBox = ListView2.Items(ListView2.Items.Count - 1).SubItems(0)
StatusBox.ForeColor = Color.Cyan
StatusBox.Text = "PINGING..."
Next
End Sub

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900