Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a continuous cycle, which creates the controls.
The panel is being InvokeRequired = true and the object.
how to proceed in this case.
VB
While true
 sleep(2000)
 dim myType as myType
 sTh = New Thread(New ParameterizedThreadStart(AddressOf AddMoreControls))
 sTh.Start(myType)
Wend

  
 Delegate Sub sAddControl(ByVal pParam() As Object)
 Private Sub ssAddControl(ByVal pParam() As Object)
	 Try
		 Dim pn As Panel = CType(pParam(0), Panel)
		 Dim ctl As MyControl = CType(pParam(1), MyControl)
		 pn.Controls.Add(ctl)
	 Catch ex As Exception
		Throw ex
	 End Try
 End Sub

 Private Sub AddMoreControls(byval myType as myType)
	 try
		 Dim ctl As New MyControl
		 ctl.Name = "txt_1"
		 ctl.myType = myType

		 if GroupBox.InvokeRequired then

		 Dim pParam(1) As Object
			 pParam(0) = myPanel
			 pParam(1) = ctl
			 Dim d As New sAddControl(AddressOf ssAddControl)
			 GroupBox.Invoke(d, New Object() {pParam})
		 else
			myPanel.add(ctl)
		 end if 
	Catch ex As Exception
		msgbox (ex)
	End Try
 end sub


[Edit]Code block added[/Edit]
Posted
Updated 30-Nov-12 6:04am
v2
Comments
Sergey Alexandrovich Kryukov 5-Feb-13 0:17am    
How come you post non-answer (a comment) as "solution", and even accepted it formally?!
Don't do it, please. This is considered as abuse, and some even lost their memberships as a result of abuse report.
—SA

You really can't do any of this on a background thread. All controls MUST be created on the UI thread or you'll run into all kinds of problems that are extremely difficult to debug and can't fix.

You can still do this from a background thread, but you must Invoke a method on the UI thread to create the controls. You cannot touch any control or control container (like adding controls to a form, panel, group box, ...) from anything other than the UI thread.
 
Share this answer
 
the AddMoreControls runs in a new Thread, the control (ctl) created in this function will not be in the same thread as the Panel (the UI Thread).
That's why I think you have the invalid operation.
You should include the creation of the control in the Invoked method.
VB
Delegate Sub sAddMoreControl(ByVal myType as myType)
Private Sub AddMoreControls(byval myType as myType)
try
  if GroupBox.InvokeRequired then
    Dim d As New sAddMoreControl(AddressOf AddMoreControls)
    GroupBox.Invoke(d, New Object() {myType})
  else
    Dim ctl As New MyControl
    ctl.Name = "txt_1"
    ctl.myType = myType
    myPanel.add(ctl)
  end if
Catch ex As Exception
  msgbox (ex)
End Try
end sub 


Sorry if I made some syntax error in VB.NET, I use C# syntax more.
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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