使用此代码,抛出索引超出范围错误,建议?添加了整个代码。在选择列表框项目时,仅将最后一项输入到数据库中。我怀疑它与代码末尾的受影响的整数和受影响的调用有关。
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
答案 0 :(得分:2)
您需要将If语句放在循环中。 x
循环变量仅在循环内递增或递减,具体取决于Step
。
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.GetSelected(x) = False Then
ListBox1.SetSelected(x, True)
End If
Next