1

Good day. Would like to ask for help in resolving the error of the data set in Combo-box in WinForm, I got from web-page Combo-box. The whole point is that the data from the site I parsed, stuffed in List, but I can not set because of this error

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

But more interesting and puzzles me, I have to manually push data to List, and then when I press the button - the data is displayed.

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

And if I put the data into List dynamically - got an error

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

Tell me please how to organize the 2nd thread in this case. Thank you. Oh.. and sorry for my English :)

rpax
  • 4,468
  • 7
  • 33
  • 57
Num2
  • 13
  • 2
  • possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – Dmitry Mar 29 '14 at 12:56

1 Answers1

1

Call BeginInvoke on your combobox object to execute a delegate on UI tread like so

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

this will execute the delegate asynchronously. If you want the delegate to be executed synchronously call Invoke instead.

vadim
  • 176
  • 6