Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidArgument=Value of '0' is not valid for 'SelectedIndex'

Tags:

c#

.net

winforms

I'm working on a Windows Forms application in .NET 4.0. As I am binding data to a BindingSource (to which a ComboBox is bound), I get the following exception. Note: I get it only if I make the debugger stop at exceptions being thrown, either unhandled or handled. Thus, the exception is caught somewhere - but nevertheless I'm not sure whether it is OK to be thrown.

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

I'm not setting the SelectedIndex property. My code is shown below. myData is an IList of entities (List at runtime):

myBindingSource.DataSource = myData;

I can't figure out what I'm doing wrong. Moreover, the Call Stack is confusing me a bit (see it below). The Windows Forms framework seems to be setting SelectedIndex on the combo box, which causes the exception. Does anybody know a way of getting rid of this?

Cheers Matthias

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)
like image 857
Matthias Meid Avatar asked Mar 11 '11 14:03

Matthias Meid


1 Answers

When you ask the debugger to stop on Exceptions, it will do so, regardless whether they will be handled or not. This leads to scenarios like the one you observed:
The debugger stops at an exception and confuses you, although the exception is perfectly valid and seems to be expected by the surrounding code, because it handles the exception without dying.

To sum up and answer your question:
Not all exceptions the debugger stops at are an indicator that you are doing something wrong or that there is a problem in your code.

Update (credits go to Mark):
You can tell the debugger to only catch your exceptions, if you enable the option "Just my code".

like image 140
Daniel Hilgarth Avatar answered Oct 01 '22 14:10

Daniel Hilgarth