Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i want to add some controls to flowlayoutpanel from async thread, but di get an error that say "Cross-thread operation not valid: Control 'ect' accessed from a thread other than the thread it was created on.".
Please help me

Antonio from italy
Posted

Its relatively simple, you have to invoke the adding/removing/modifying of a control on the UI thread:

C#
flowLayoutPanel1.Invoke((MethodInvoker) delegate {
    //Code to add your control to the panel here.
});


You can construct the control outside of the invoke, and only put the add inside the invoke delegate. This is just one way of doing it, there are other ways. For example, before calling flowLayoutPanel1.Invoke you should check first if a cross-thread operation will really occur by checking the value of flowLayoutPanel1.InvokeRequired. If that is true, then do the above, if not, just add it directly to the panel.
 
Share this answer
 
Comments
prometeo2000 21-Jan-14 15:29pm    
Hi Ron,
Thank you for your suggest, i have try it and ... work fine!!!
Here my code...

Ti ringrazio anche in Ialiano... nel caso avessi commesso qualche errore in inglese, visto che non è una lingua che conosco benissimo. Ciao

Imports System.Threading

Public Class Form1

Dim t As Thread
Delegate Sub AddControlsCallBack([btn] As Button)


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

StopThread()
FlowLayoutPanel1.Controls.Clear()

t = New Thread(AddressOf AddControls)
t.Start()


End Sub

Private Sub AddControls()

For i As Integer = 0 To 100

Dim b As New Button
b.Text = "Button" & i

Thread.Sleep(1000) 'some hard work

If FlowLayoutPanel1.InvokeRequired Then
Dim ctrlCallBack As New AddControlsCallBack(AddressOf addButtons)
Me.Invoke(ctrlCallBack, New Object() {b})
Else
FlowLayoutPanel1.Controls.Add(b)
End If

Next

End Sub


Private Sub addButtons(ByVal b As Button)

FlowLayoutPanel1.Controls.Add(b)

End Sub

Private Sub StopThread()

If Not t Is Nothing Then
If t.IsAlive Then t.Abort()
End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

StopThread()

End Sub


End Class

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