ArgumentException when Filling DataTable bound to ComboBox or ListBox

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
While debuging an application that I am working on I noticed that I was continually recieving an ArgumentOutOfRange Exception. So I changed the debug setting to stop on all first chance exceptions so that I could find what was generating the error. I was
mildly supprised when execution stoped on the declaration of returnValue in the following code snipet.
<pre class="prettyprint lang-vb <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, false)> _
Public Overloads Overridable Function FillByFileID(ByVal dataTable As EERecipeDBDataSet.DataSetsDataTable, ByVal FileID As Global.System.Nullable(Of Integer)) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(2)
If (FileID.HasValue = true) Then
Me.Adapter.SelectCommand.Parameters(1).Value = CType(FileID.Value,Integer)
Else
Me.Adapter.SelectCommand.Parameters(1).Value = Global.System.DBNull.Value
End If
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function[/code]
The error that it gave stated the following:
InvalidArgument=Value of 0 is not valid for SelectedIndex.<br/>
Parameter name: SelectedIndex
Now, with the debug set to ignore first chance exceptions, microsoft apparently handles this error, and everything seems to work alright, but I would rather there were no exceptions thrown, at least durring development testing. So I went looking for
a solution.
What I found supprised, and to be honest, somewhat frustrated me. Every time I need to Fill a data table bound to either a combobox or listbox I have to change my code from a single line calling the Fill routine of the TableAdapter to this:
<pre class="prettyprint lang-vb Me.lstDataSets.DataSource = Nothing
Me.lstDataSets.DisplayMember = Nothing
Me.lstDataSets.ValueMember = Nothing
Me.DataSetsTableAdapter.FillByFileID(Me.dsEERecipeDB.DataSets, CurrentFileID)
Me.lstDataSets.DataSource = bsDataSets
Me.lstDataSets.DisplayMember = "Data_Set_Name"
Me.lstDataSets.ValueMember = "Data_Set_ID"[/code]
It does not matter if the table is emby or not. And, interestingly enough, the error does not occure if the table is bound to a datagridview.
I suppose that my real curiosity is if this is by design or not? Why would a function filling a DataTable care about what was bound to it? Is it not the binding objects responsibility to insure data in the table is valid to be displayed by it? <hr class="sig Programming is easy, understanding how is not.

View the full article
 
Back
Top