c# - InvalidArgument= '0' 的值对于 'SelectedIndex' 无效

标签 c# .net winforms

我正在 .NET 4.0 中开发 Windows 窗体应用程序。当我将数据绑定(bind)到 BindingSource(绑定(bind)了 ComboBox)时,出现以下异常。注意:只有当我让调试器在抛出异常时停止,无论是未处理还是已处理,我都会得到它。因此,异常在某处被捕获 - 但我不确定是否可以抛出。

ArgumentOutOfRangeException occurred InvalidArgument=Value of '0' is not valid for 'SelectedIndex'. Parameter name: SelectedIndex

我没有设置 SelectedIndex 属性。我的代码如下所示。 myData 是实体的 IList(List 在运行时):

myBindingSource.DataSource = myData;

我不知道我做错了什么。此外,调用堆栈让我有点困惑(见下文)。 Windows 窗体框架似乎在组合框上设置 SelectedIndex,这会导致异常。有人知道摆脱这种情况的方法吗?

干杯 马蒂亚斯

System.Windows.Forms.dll!System.Windows.Forms.ComboBox.SelectedIndex.set(int value) + 0x233 bytes   
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs e) + 0x3e bytes    
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) + 0x1bd bytes    
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x75c bytes   
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.ResetBindings(bool metadataChanged) + 0x3e bytes    
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.SetList(System.Collections.IList list, bool metaDataChanged, bool applySortAndFilter) + 0x22c bytes 
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.DataSource.set(object value) + 0x47 bytes   
(my method)

最佳答案

当您要求调试器遇到异常时停止,它会这样做,无论它们是否会被处理。这会导致类似于您观察到的场景:
调试器在异常处停止并使您感到困惑,尽管异常是完全有效的并且似乎是周围代码所期望的,因为它处理了异常而没有死。

总结并回答你的问题:
并非所有调试器停止的异常都表明您做错了什么或代码中存在问题。

更新(致谢马克):
如果您启用“仅我的代码”选项,您可以告诉调试器只捕获您的异常。

关于c# - InvalidArgument= '0' 的值对于 'SelectedIndex' 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5274357/

相关文章:

c# - 为什么这个多态的 C# 代码会打印出它的作用?

winforms - 在全 GUI Powershell 脚本中隐藏空控制台窗口?

c# - 带不透明度的 WinForm 控件

c# - 如何将 ProgressBar 放在 Button 中

c# - Linq to Entities - 将 string[] 中带有 TagID 的所有对象插入 ICollection<Tag>

html - 使用 mailto : under ASP. NET 的邮件主题中出现乱码

c# - 在 C# 中存储对对象的引用

c# - 如何在多个线程之间进行通信?

c# - EF Core 关系查询

c# - MVVM - 绑定(bind)到聚合属性