我的checkedlistbox在我的项目中包含五个项目A,B,C,D,E。 这是我的编程代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Admin\Documents\testing.accdb;Jet OLEDB:Database Password=*****")
Dim cmd As New OleDbCommand("", con)
cmd.CommandText = "INSERT INTO test (combo, L1, L2, L3, L4) VALUES (@combo, @L1, @L2, @L3, @L4)"
For i = 0 To CheckedListBox1.CheckedIndices.Count - 1
If i = 0 Then
cmd.Parameters.AddWithValue("@combo", CheckedListBox1.CheckedItems(i).ToString)
ElseIf i = 1 Then
cmd.Parameters.AddWithValue("@L1", CheckedListBox1.CheckedItems(i).ToString)
ElseIf i = 2 Then
cmd.Parameters.AddWithValue("@L2", CheckedListBox1.CheckedItems(i).ToString)
ElseIf i = 3 Then
cmd.Parameters.AddWithValue("@L3", CheckedListBox1.CheckedItems(i).ToString)
ElseIf i = 4 Then
cmd.Parameters.AddWithValue("@L4", CheckedListBox1.CheckedItems(i).ToString)
End If
Next
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
'code end
所以我的问题是,当我检查了checkedlistbox中的所有项目时,这段代码对我很有用,但是当我选择少于五个项目时,它会给出错误" 没有给出一个或多个必需参数的值"
请告诉我该怎么做?
答案 0 :(得分:0)
尝试更改循环代码:
'set default value
cmd.Parameters.AddWithValue("@combo", "false")
cmd.Parameters.AddWithValue("@L1", "false")
cmd.Parameters.AddWithValue("@L2", "false")
cmd.Parameters.AddWithValue("@L3", "false")
cmd.Parameters.AddWithValue("@L4", "false")
For i = 0 To CheckedListBox1.CheckedItems.Count - 1
Select Case CheckedListBox1.CheckedIndices(i)
Case 0
cmd.Parameters.AddWithValue("@combo", CheckedListBox1.CheckedItems.Item(i).ToString)
Case 1
cmd.Parameters.AddWithValue("@L1", CheckedListBox1.CheckedItems.Item(i).ToString)
Case 2
cmd.Parameters.AddWithValue("@L2", CheckedListBox1.CheckedItems.Item(i).ToString)
Case 3
cmd.Parameters.AddWithValue("@L3", CheckedListBox1.CheckedItems.Item(i).ToString)
Case 4
cmd.Parameters.AddWithValue("@L4", CheckedListBox1.CheckedItems.Item(i).ToString)
End Select
Next