views:

2480

answers:

4

System.InvalidOperationException: DragDrop registration did not succeed. ---> System.Threading.ThreadStateException:

What does this exception mean? I get it at this line trying to add a panel to a panel at runtime... splitReport.Panel1.Controls.Add(ChartPanel);

Working in VS2008 C#

+1  A: 

Perhaps this will help: http://www.datadynamics.com/forums/101814/ShowPost.aspx

Michael
A: 

Do you have an STA attribute on your Main method?

Ilya Ryzhenkov
yes I do...[STAThread]static void Main( ) { Application.Run(new WindowsApplication());}
Laurie
+10  A: 

This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.

If you have the [STAThread] attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):

Thread.CurrentThread.SetApartmentState( ApartmentState.STA )

(Thread and ApartmentState are members of System.Threading)

That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the [STAThread] attribute.

If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.

Charlie
If you don't want to fuss with setting it manually, you can also put the [STAThread] attribute on the thread method.
Tomer Pintel
A: 

I'm not sure whether you have solved this problem or not. I just encountered this problem and I fixed it by deleting my bin directory.

Ngu Soon Hui