将动态List中的数据设置为Combobox时出错

时间:2014-03-29 12:44:22

标签: c# multithreading winforms list combobox

美好的一天。 想要帮助解决WinForm中Combo-box中数据集的错误,我从网页组合框中得到了。整点是来自我解析的网站的数据,填充在List中,但由于此错误我无法设置

"Invalid operation in several threads: 
attempt to access control "combo-box" from another thread 
in which it was created."

但更有趣并且让我感到困惑,我必须手动将数据推送到List,然后当我按下按钮时 - 显示数据。

public class ComboItem
{
   public string Name { get; set; }
   public int Id { get; set; }
   public ComboItem(string text, int value)
   {
       Name = text;
       Id = value;
   }
}

private void button3_Click(object sender, EventArgs e)
{
    List<ComboItem> items = new List<ComboItem>();
    BindingSource bs = new BindingSource();
    items.Add(new ComboItem("John", 1));

    bs.DataSource = items;
    cb_category.DataSource = bs.DataSource;
    cb_category.DisplayMember = "Name";
    cb_category.ValueMember = "Id";
}

如果我动态地将数据放入List中 - 得到错误

public class ComboItem
{
   public string Name { get; set; }
   public int Id { get; set; }
   public ComboItem(string text, int value)
   {
      Name = text;
      Id = value;
   }
}

/*-----------MY Function--------------*/
for (int i = 0; i < idCategory.Count-1; i++)
{
   int num = Convert.ToInt32(idCategory[i]);
   nameCategory = SearchAndInput(dataCategory.InnerHtml, "<option value=""+num+"">", "rn");
   items.Add(new ComboItem(nameCategory[0].ToString(), num));
}

BindingSource bs = new BindingSource();
bs.DataSource = items;
cb_category.DataSource = bs.DataSource;
cb_category.DataSource = items;
cb_category.DisplayMember = "Name";
cb_category.ValueMember = "Id";

请告诉我如何在这种情况下组织第二个主题。谢谢。哦..对不起我的英语:)

1 个答案:

答案 0 :(得分:1)

在你的组合框对象上调用BeginInvoke以在UI踏板上执行委托 像这样

cb_category.BeginInvoke((Action)delegate 
{
    cb_category.DataSource = items;
    cb_category.DisplayMember = "Name";
    cb_category.ValueMember = "Id";
});

这将异步执行委托。如果您希望同步执行委托,请改为呼叫Invoke