2
votes

I'm creating a combobox programmatically like this:

var cbo = new ComboBox {
    DataSource = mylist,
    SelectedIndex = mylist.IndexOf(myvalue)
};

I'm not setting ValueMember so that the value will be the object itself. When I do the above I get the following exception on the SelectionIndex line:

InvalidArgument=Value of '3' is not valid for 'SelectedIndex'. Parameter name: SelectedIndex

Is it because the combobox is still being created and therefore the DataSource is still not populated? If yes, what's the correct way to set the index?

1

1 Answers

1
votes

Databiding will not work until after the control becomes visible. So you need to change your code to:

var mylist = Enumerable.Range(1, 5).ToList();
var myvalue = 2;
var cbo = new ComboBox();
cbo.HandleCreated += (obj, args) =>
{
    BeginInvoke(new Action(() =>
    {
        cbo.DataSource = mylist;
        cbo.SelectedIndex = mylist.IndexOf(myvalue);
    }));
};
this.Controls.Add(cbo);

Then as soon as the control becomes visible, the initialization code will run and ComboBox will be populated by data source items and its selected index will be set as expected.