关于c#:ListBox添加到DataSource时抛出ArgumentOutOfRangeException

ListBox throwing ArgumentOutOfRangeException when adding to DataSource

我正在尝试在C#WinForms中将BindingList用作ListBoxDataSource,但是每当我尝试向BindingList中添加项目时,都会抛出ArgumentOutOfRangeException。下面的代码演示了该问题(假定为带有ListBox listBox1的表单):

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

请注意,如果DataSource中已经有项目,则不会出现异常:

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

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

是否有一种(非黑客方式)在ListBox上使用空的DataSource的方式,以便向其添加项目不会引发异常?

编辑:堆栈跟踪:

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


事实证明,我在"例外"对话框中检查了所有内容(调试->例外)。因此,该异常存在,但是(静默)由.Net框架处理。继续执行程序将显示预期结果。


我遇到了同样的问题,经过多次研究,我发现避免此.Net错误的唯一解决方法是,当列表不为空时,仅将BindingList分配给DataSource。

如果可以更改,则可以创建一个始终保留在列表中的虚拟对象,并在列表不为空时将其删除。

最后,寻找避免抛出ArgumentOutOfRangeException的方法是不值得的。


您是否可能在ListBox上的某个事件上附加了事件处理程序,而该事件处理程序可能导致此情况?我无法重现您正在描述的行为。

我创建了一个完全空白的WinForms项目,将一个ListBox绑定到一个BindingList<string>,将值" Test"添加到列表中(设置了ListBox.DataSource属性后),并且出现了" Test"项在框中,如预期的那样。

我将查看您的ListBoxBindingList<string>,看看其中一个是否具有某些可能附加的事件处理程序。