【问题标题】:InvalidArgument=Value of '0' is not valid for 'SelectedIndex'InvalidArgument=“0”的值对“SelectedIndex”无效
【发布时间】:2011-03-11 14:46:27
【问题描述】:

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

发生 ArgumentOutOfRangeException InvalidArgument=“0”的值对“SelectedIndex”无效。 参数名称:SelectedIndex

我没有设置SelectedIndex 属性。我的代码如下所示。 myDataIList 的实体(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)

【问题讨论】:

  • 当你绑定你的组合时,它会自动将 selectedIndex 设置为第 0 项。如果你的数据源中没有项目,你为什么不做检查不绑定?

标签: c# .net winforms


【解决方案1】:

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

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

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

【讨论】:

  • 马克,你的名字!出于任何原因,我出于任何原因关闭了“只是我的代码”并忘记了它。谢谢!
【解决方案2】:

你也可以试试这个。在设置组合框 DataSource 之前设置它的 BindingContext

myBindingSource.BindingContext = this.BindingContext;
myBindingSource.DataSource = myData;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多