我需要从checkedlistbox向Access数据库插入数据。 checkedlistboxes中的项目是外键,按名称显示,而不是按ID显示。我需要做的是当我点击"添加"按钮,它应该插入项目' ID及其名称作为字符串(str)到数据库中的Services_Availed表,但即使插入了新数据也不会显示名称(每次单击添加按钮时都会添加另一个ServicesAvailed_ID)。
以下是我的尝试:
Private Sub btnAddService_Click(sender As Object, e As EventArgs) Handles btnAddService.Click
Try
Dim con As New OleDb.OleDbConnection
Dim str As String = ""
Dim i As Integer
If chcklstbx1.CheckedItems.Count > 0 Then
For i = 0 To i < chcklstbx1.CheckedItems.Count
If str = "" Then
str = chcklstbx1.CheckedItems(i).ToString
Else
str += "," + chcklstbx1.CheckedItems(i).ToString
End If
Next
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\rose&mike\Desktop\DbSysDel3\salondbaccess.accdb"
con.Open()
Dim cmd As New OleDb.OleDbCommand
cmd = New OleDbCommand("Insert Into Services_Availed(AvailedNames) Values(@ServiceType_Name)", con)
cmd.Parameters.AddWithValue("@ServiceType_Name", str)
cmd.ExecuteNonQuery()
MessageBox.Show("Data inserted successfully")
con.Close()
Else
MessageBox.Show("Please select at least one item")
While (chcklstbx1.CheckedItems.Count > 0)
chcklstbx1.SetItemChecked(chcklstbx1.CheckedIndices(0), False)
End While
End If
Catch ex As Exception
End Try
End Sub
任何建议都将受到高度赞赏。
答案 0 :(得分:0)
您可以将FOR语句缩减为:
For i = 0 to chcklstbx1.CheckedItems.Count - 1