c# – 添加到DataSource时抛出ArgumentOutOfRangeException的ListBox

我正在尝试使用BindingList作为C#WinForms中ListBox的DataSource,但每当我尝试将项添加到BindingList时,我都会抛出ArgumentOutOfRangeException.以下代码演示了该问题(假设使用ListBox listBox1的表单):

BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.

请注意,如果dataSource中已有项目,我不会得到异常:

BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.

我可以通过在添加项目之前将DataSource属性设置为null并在之后重新设置DataSource来解决此问题,但这感觉就像一个hack,我希望能够避免这样做.

是否有(非黑客)方法在ListBox上使用空数据源,这样向其添加项不会抛出异常?

编辑:堆栈跟踪:

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

最佳答案 事实证明我在“例外”对话框中检查了所有内容(Debug-> Exceptions).因此,异常存在,但是(由#Net)框架(静默地)处理.继续执行程序会显示预期结果.

点赞