this->Controls->Add ERROR System.InvalideOperationException-Collection of common programming errors
.png)
msdn hello,I am developing code to add various controls to a windows form at runtime and I am recieving an error of “System.InvalidOperationException.” When I remove checking of illegal thread calls, I recieve and error of this “System.ArgumentException.” Location of Error is shown below.I have this code also in the form load section and it executes fine. I then call this:
ExecThreadDelegate* execThread =
new ExecThreadDelegate(this,&ProtoBRAT::StatusForm::ExecThread);execThread->BeginInvoke(0, 0);I am unable to add controls. Do i have to make another thread to add components?
System::Collections::Generic::List* OpLabels;System::Windows::Forms::Label* temp; OpLabels = new System::Collections::Generic::List;
temp = new Label();…….
…….temp->Location = System::Drawing::Point(Xcoord, Ycoord);
temp->Name = S
“name”;temp->Size = System::Drawing::Size(150, 16);
temp->Text = S
“text”;
this->Controls->Add(temp); // ERROR OCCURS HEREOpLabels->Add(temp);please let me know.thanks!
.png)
msdn1 What you are doing is a serious mistake. Luckily, Windows itself caught it after you tried to shut up the IllegalOperation exception. Windows is balking because you are creating a child control on a different thread than the parent control (the form). This is illegal in Windows. Before you set the CheckForIllegalCrossThreadCalls property to false, .NET was warning you that you were accessing a control from a thread that didn’t create it.This can cause serious and random failure of your program. It may run for hours or minutes. You may notice strange painting problems here or there. Sooner or later, the moon crosses in front of the sun and your program will deadlock solidly, requiring the three finger salute.The threading rules are simple: only ever create controls on the UI thread. Only ever access controls on the UI thread. If a background thread needs to update a control, it must use Control.Invoke() or BeginInvoke(). Be sure to not mess with CheckForIllegalCrossThreadCalls, it warns you when you break the rules, even if by accident.
Hans Passant.