I'm trying use a BindingList as a DataSource for a ListBox in C# WinForms, but whenever I try to add items to the BindingList, I get an ArgumentOutOfRangeException thrown. The following code demonstrates the problem (assume a form with ListBox listBox1):
BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.
Note that if dataSource already has items in it, I do not get the exception:
BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.
I can work around the problem by setting the DataSource property to null before adding an item, and re-setting the DataSource afterward, but this feels like a hack, and I'd like to be able to avoid doing so.
Is there a (non-hack) way to use an empty DataSource on a ListBox, such that adding items to it doesn't throw exceptions?
Edit: Stack Trace:
System.Windows.Forms.dll!System.Windows.Forms.ListBox.SelectedIndex.set(int value) + 0x1ec bytes
System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object sender, System.EventArgs e) + 0x2e bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs e) + 0x39 bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) + 0x14f bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x2e4 bytes
System.dll!System.ComponentModel.BindingList.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x17 bytes
System.dll!System.ComponentModel.BindingList.FireListChanged(System.ComponentModel.ListChangedType type, int index) + 0x35 bytes
System.dll!System.ComponentModel.BindingList.InsertItem(int index, System._Canon item) + 0x3f bytes
mscorlib.dll!System.Collections.ObjectModel.Collection.Add(System._Canon item) + 0x76 bytes