I'm trying to use a BindingList as a DataSource for a ListBox in C # WinForms, but whenever I try to add items to a BindingList , I get an ArgumentOutOfRangeException throw. The following code demonstrates the problem (suppose the form is with ListBox listBox1 ):
BindingList<string> dataSource = new BindingList<string>(); listBox1.DataSource = dataSource; dataSource.Add("Test1");
Note that if the DataSource already has elements in it, I do not get an exception:
BindingList<string> dataSource = new BindingList<string>(); dataSource.Add("Test1"); listBox1.DataSource = dataSource; dataSource.Add("Test2");
I can work around the problem by setting the DataSource property to null before adding the item and then setting the DataSource again, but this seems like a hack, and I would like to be able to avoid this.
Is there a way (without a hack) to use an empty DataSource on a ListBox so that adding elements to it does not throw exceptions?
Edit : Stack Trace:
System.Windows.Forms.dll! System.Windows.Forms.ListBox.SelectedIndex.set (intermediate 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 (intermediate newPosition, check bool, 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, index int) + 0x35 bytes
System.dll! System.ComponentModel.BindingList.InsertItem (intermediate index, System._Canon item) + 0x3f bytes
mscorlib.dll! System.Collections.ObjectModel.Collection.Add (System._Canon item) + 0x76 bytes
source share