Separate problem with the apartment

From my main form, I call the following to open a new form

MyForm sth = new MyForm(); sth.show(); 

Everything works fine, but there is a combobox on this form, which when I switch my AutoCompleteMode to suggest and add, I got this exception showing the form:

The current thread must be set to single-threaded apartment (STA) before OLE calls can be made. Make sure your main function has the STAThreadAttribute marked on it.

I set this attribute in my main function as requested by the exception:

 [STAThread] static void Main(string[] args) { ... 

May I get some help to figure out what might be wrong.

Code example:

 private void mainFormButtonCLick (object sender, EventArgs e) { // System.Threading.Thread.CurrentThread.SetApartmentState(ApartmentState.STA); ? MyForm form = new MyForm(); form.show(); } 

Designer:

 this.myCombo.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.myCombo.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.myCombo.FormattingEnabled = true; this.myCombo.Location = new System.Drawing.Point(20, 12); this.myCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.myCombo.Name = "myCombo"; this.myCombo.Size = new System.Drawing.Size(430, 28); this.myCombo.Sorted = true; this.myCombo.TabIndex = 0; phrase"; 

Data Source Setup

 public MyForm(List<string> elem) { InitializeComponent(); populateColorsComboBox(); PopulateComboBox(elem); } public void PopulateComboBox(List<string> list ) { this.myCombo.DataSource = null; this.myCombo.DisplayMember = "text"; this.myCombo.DataSource = list; } 
+8
multithreading c # thread-safety winforms
source share
3 answers

Is Main(string[] args) your entry point?

Perhaps you have another Main () overload with no parameters. Or some other Main () in another class. Open the project properties and find the starting object.

+3
source share

Windows Forms applications must run in the STA method.

See here: Could you explain STA and MTA?

And COM comes into play as window shapes come into play because the controls themselves use their own window handles and therefore must adhere to the STA model. I believe that the reason you get the error in this particular place is because the second thread is created / used internally by autocomplete.

And, as I understand it, the streaming model should be set to Main, changing it later only works from STA to MTA, but not vice versa.

+2
source share

As a wild thought: create a deep copy of the original list in the second form and attach the drop-down field to the copy of the list, not the original.

+1
source share

All Articles