Reputation: 57
Working with this code, throwing index out of range error, suggestions? Added the entire code. While the listbox items are all selected only the last one is input into the database. I suspect it has something to do with the Affected as Integer and the Affected call at the end of the code.
Dim Affected As Integer = 0
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CalcDB.accdb"),
.PersistSecurityInfo = False
}
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
INSERT INTO CalcOps
(
NumOne,
Operation,
NumTwo,
Equal,
Result
)
VALUES
(
@NumOne,
@Operation,
@NumTwo,
@Equal,
@Result
)
</SQL>.Value
With cmd.Parameters
.AddWithValue("@NumOne", NumOne.Text)
.AddWithValue("@Operation", ListBox1.Tag)
.AddWithValue("@NumTwo", NumTwo.Text)
.AddWithValue("@Equal", "=")
.AddWithValue("@Result", Result.Text)
End With
Dim x As Integer
For x = 0 To ListBox1.Items.Count - 1
If ListBox1.GetSelected(x) = False Then
ListBox1.SetSelected(x, True)
End If
Next
Try
cn.Open()
Affected = cmd.ExecuteNonQuery
Catch ex As Exception
MessageBox.Show("Problem:" & Environment.NewLine & ex.Message)
End Try
End Using
End Using
If Affected = 1 Then
MessageBox.Show("Insert done")
Else
MessageBox.Show("Insert failed")
End If
End Sub
Upvotes: 0
Views: 2232
Reputation: 9024
You need to place the If statement inside the loop. The x
loop variable only increments or decrements, depending on Step
, inside the loop.
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.GetSelected(x) = False Then
ListBox1.SetSelected(x, True)
End If
Next
Upvotes: 2