Num2
Num2

Reputation: 13

Error setting data from dynamic List to Combobox

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 :)

Upvotes: 1

Views: 154

Answers (1)

vadim
vadim

Reputation: 176

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.

Upvotes: 1

Related Questions