我遇到CheckedListBox问题。如何将SelectedValues转换为更新查询?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim promozione As String
dest = "INSERT INTO dbo.dest " &
"([ID], [Cod], [SellIn], [SellOut]) " &
"VALUES (@ID, @Cod, @SellIn, @SellOut)"
Dim ins As New SqlDataAdapter(dest, con)
Dim run As New SqlCommand(dest, con)
con.Open()
For Each Cod In CheckedListBox1.CheckedItems()
run.Parameters.Add(New SqlParameter("@ID", ComboBox1.SelectedValue))
run.Parameters.Add(New SqlParameter("@Cod", CheckedListBox1.SelectedValue))
run.Parameters.Add(New SqlParameter("@SellIn", DateTimePicker1.Text))
run.Parameters.Add(New SqlParameter("@SellOut", DateTimePicker2.Text))
run.ExecuteNonQuery()
Next
con.Close()
End Sub
单击Button2时,将返回错误:
System.Data.dll中的'System.Data.SqlClient.SqlException'已经声明了变量名'@ID'。
答案 0 :(得分:2)
您应该清除每次迭代的参数集合,我相信如下所示。实际上,更好的方法是在循环外创建这些参数,然后在每次迭代中设置它们的值。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim promozione As String
dest = "INSERT INTO dbo.dest " &
"([ID], [Cod], [SellIn], [SellOut]) " &
"VALUES (@ID, @Cod, @SellIn, @SellOut)"
Dim ins As New SqlDataAdapter(dest, con)
Dim run As New SqlCommand(dest, con)
con.Open()
For Each Cod In CheckedListBox1.CheckedItems()
run.Parameters.Clear()
run.Parameters.Add(New SqlParameter("@ID", ComboBox1.SelectedValue))
run.Parameters.Add(New SqlParameter("@Cod", CheckedListBox1.SelectedValue))
run.Parameters.Add(New SqlParameter("@SellIn", DateTimePicker1.Text))
run.Parameters.Add(New SqlParameter("@SellOut", DateTimePicker2.Text))
run.ExecuteNonQuery()
Next
con.Close()
End Sub
答案 1 :(得分:0)
如何从CHECKEDLISTBOX中插入SQL QUERY多个选定项目! 两天后,这就是解决方案:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dest As String
dest = "INSERT INTO dbo.dest " &
"([ID], [Cod], [SellIn], [SellOut]) " &
"VALUES (@ID, @Cod, @SellIn, @SellOut)"
Dim ins As New SqlDataAdapter(dest, con)
Dim run As New SqlCommand(dest, con)
con.Open()
For Each Cod As DataRowView In CheckedListBox1.CheckedItems()
run.Parameters.Clear()
run.Parameters.Add(New SqlParameter("@ID", ComboBox1.SelectedValue))
run.Parameters.Add(New SqlParameter("@Cod", Cod("IDCod"))) '<------ IDCods are the CheckedListBox1.ValueMembers'
run.Parameters.Add(New SqlParameter("@SellIn", DateTimePicker1.Text))
run.Parameters.Add(New SqlParameter("@SellOut", DateTimePicker2.Text))
run.ExecuteNonQuery()
Next
con.Close()
End Sub