ListBox throwing ArgumentOutOfRangeException when adding to DataSource
我正在尝试在C#WinForms中将
1 2 3 | BindingList<string> dataSource = new BindingList<string>(); listBox1.DataSource = dataSource; dataSource.Add("Test1"); // Exception, here. |
请注意,如果
1 2 3 4 | BindingList<string> dataSource = new BindingList<string>(); dataSource.Add("Test1"); listBox1.DataSource = dataSource; dataSource.Add("Test2"); // Appears to work correctly. |
我可以通过在添加项目之前将
是否有一种(非黑客方式)在
编辑:堆栈跟踪:
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的方法是不值得的。
您是否可能在
我创建了一个完全空白的WinForms项目,将一个
我将查看您的