Reputation: 7240
I have a WinForms combobox that is bound to a list of objects list this:
BindingList<myObject> myListOfObjects = new BindingList<myObject>();
// 100 objects are added to myListOfObjects
bindingSource1.DataSource = myListOfObjects;
comboBox1.DataSource = bindingSource1;
comboBox1.DisplayMember = "Name";
Each instance of my object contains the following:
public string Name
public int Index
public List<int> Codes = new List<int>();
The object also implements INotifyPropertyChanged.
When an objects "Name" is selected in the combobox, I want to databind a listbox to the "Codes" list for the selected object. I'm trying to do this as such:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.DataSource = myListOfObjects[((myObject)comboBox1.SelectedValue).Index].Codes;
}
This doesn't work and I get an InvalidCastException (specifically that Int32 can't be cast as myObject). Am I going about this all wrong?
Upvotes: 1
Views: 186
Reputation: 44931
The problem is that combobox1.SelectedValue
will be set to the myObject
property that is specified in the ValueMember
of the combobox.
In order to get the underlying myObject
, you need to use comboBox1.SelectedItem
:
listBox1.DataSource = myListOfObjects[((myObject)comboBox1.SelectedItem).Index].Codes;
If this were my code, I would also double-check to ensure that SelectedItem is not null before using it directly:
if (comboBox1.SelectedItem != null) {
listBox1.DataSource = myListOfObjects[((myObject)comboBox1.SelectedItem).Index].Codes;
} else {
listBox1.DataSource = null;
}
Upvotes: 2