I am trying to populate a combobox in C#, but for some reason, the items do not appear.
public List<string> items
{
set
{
combobox.Items.Clear();
foreach(string s in value)
{
combobox.Items.Add(s);
}
combobox.Update();
}
}
This seems like incredibly straightforward code. I simply cannot see what is wrong.
It is being called like this:
private void StoreNames(List<string> names)
{
if (selectionForm.InvokeRequired)
selectionForm.Invoke((MethodInvoker)delegate { selectionForm.items = names; });
else
selectionForm.items = names;
}
Interestingly, it seems to work when InvokeRequired returns true, but does not work when it returns false.
EDIT:
I discovered that selectionForm.IsHandleCreated is currently false. This is causing InvokeRequired to return false, but is also why calling the setter regularly isn’t working. I don’t have any idea why IsHandleCreated is set to false. The Form has been Show()n.
Not sure why your code isn’t working – I tried it and it works just fine.
However, below is some more straightforward code which also works – you may find that doing it this way instead makes your problem go away. This does presume that there is not other reason why you need to go through that property – that is quite an unusual way of doing things.
Here we just pass the list straight to the items.AddRange() method on the comboBox.
I suspect this won’t work for you – something else is going on, but I have tried it both from a backgroundworker (where InvokeRequired is true) and from the main UI thread.