0
votes

I'm getting this exception when trying to select the new item added to a listbox via its bindingsource.

This is the BindingSource with a DataSource of custom objects

BindingSource bs = new BindingSource() { DataSource = myObjectsList };
listbox.DataSource = bs;
listbox.DisplayMember = "MyObjectProperty";

When i add a new item to the BindingSource the listbox updates but i can't select the new item

bs.Add(new MyObject());
int newItemIndex = listbox.Items.Count - 1; // this returns the right index of the new added item
listbox.SelectedIndex = newItemIndex;

Here i get the System.ArgumentOutOfRangeException (InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.)

If i disable debug breaking in System exceptions the program goes on and the item get selected, but i can't understand why i'm getting that error if the listbox actually has the item.

1

1 Answers

1
votes

The error occurs because in WPF stuff happens asyncronously. If you tried to select your new item by assigning it as SelectedItem you would find that it probably wouldn't be selected. You can questions regarding this behaviour on TabControl. The reason is that just because you've added the item to the datasource that doesn't mean that the control has rendered and shown the item in the GUI. It needs to do some stuff like generate container (ListBoxItem probably) and if that hasn't happened then the item isn't truly added yet. So when you set the SelectedIndex you get the error.

tl;dr: The item hasn't been added in the GUI and as such your index is invalid. Just because the backing collection has the item that doesn't mean that it's really there ;-)