单线公寓问题

从我的mainform我打电话给以下打开一个新表格

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

一切都很好但是这个表单有一个combobox,当我将其AutoCompleteMode切换为建议和附加时,我在显示表单时遇到了这个exception:

在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式。 确保您的Main函数标记了STAThreadAttribute。

我已根据exception的请求在我的main函数上设置了此属性:

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

我可以请一些帮助来了解可能出错的地方。

示例代码:

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

设计师:

 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"; 

设置数据源

 public MyForm(List elem) { InitializeComponent(); populateColorsComboBox(); PopulateComboBox(elem); } public void PopulateComboBox(List list ) { this.myCombo.DataSource = null; this.myCombo.DisplayMember = "text"; this.myCombo.DataSource = list; } 

Main(string[] args)真的是你的切入点吗?

也许你有另一个没有参数的Main()重载。 或者另一个类中的其他一些Main()。 请打开Project属性并查找起始对象。

Windows窗体应用程序必须在STA方法中运行。

看到这里: 你能解释一下STA和MTA吗?

COM开始发挥作用,因为控件本身使用本机窗口句柄,因此必须遵守STA模型。 我相信你在这个特定地方得到错误的原因是AutoCompletion在内部创建/使用了第二个线程。

而且据我所知,线程模型必须在Main中设置,稍后更改它只能从STA到MTA,但不能反过来

作为一个疯狂的想法:在第二种forms中创建源列表的深层副本,并将combobox绑定到列表的副本而不是原始副本。