InvalidArgument =值’0’对’SelectedIndex’无效

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

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

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

 myBindingSource.DataSource = myData; 

我无法弄清楚我做错了什么。 而且,Call Stack让我感到困惑(见下文)。 Windows窗体框架似乎在combobox上设置SelectedIndex ,这会导致exception。 有人知道摆脱这个的方法吗?

干杯马蒂亚斯

 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) 

当您要求调试器停止exception时,它将执行此操作,无论它们是否将被处理。 这导致了您观察到的情景:
调试器在exception处停止并使您感到困惑,尽管exception完全有效并且似乎是周围代码所期望的,因为它处理exception而不会死亡。

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

更新(积分转到马克):
如果启用“仅我的代码”选项,则可以告诉调试器仅捕获exception。

你也可以试试这个。 在设置combobox之前,DataSource设置其BindingContext

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