2011-03-11 830 views
8

我正在使用.NET 4.0中的Windows窗体应用程序。因为我将数据绑定到BindingSource(绑定了ComboBox),所以我得到以下例外。注意:只有在调试器停止在抛出异常的情况下,我才能得到它,不管是未处理还是处理。因此,这个例外被捕获 - 但我不确定是否可以抛出。InvalidArgument ='0'的值对'SelectedIndex'无效

ArgumentOutOfRangeException发生 InvalidArgument = '0' 值不是有效的关于 '的SelectedIndex'。 参数名称:SelectedIndex

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

myBindingSource.DataSource = myData; 

我想不出什么我做错了。而且,Call Stack让我有点困惑(见下文)。 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) 
+0

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

回答

16

当你问调试器停止例外,它会这么做,无论他们是否将被处理或没有。这导致像你所观察到的一个场景:
调试器停在一个例外,迷惑你,虽然异常是完全有效的,似乎被周围的代码可以预料的,因为它处理异常没有死亡。

总结和回答你的问题:
并非所有调试程序停止的异常都表明你做错了什么或者代码有问题。

更新(积分转到标记):
如果启用选项“只是我的代码”,您可以告诉调试器只捕获您的异常。

+8

这取决于是否启用“只是我的代码”。 –

+0

马克,你的名字!出于任何原因,我出于任何原因关闭了“我的代码”并忘记了它。谢谢! –

1

你也可以试试这个。在设置ComboBox数据源之前设置它的BindingContext

myBindingSource.BindingContext = this.BindingContext; 
myBindingSource.DataSource = myData; 
相关问题