我的代码仅适用于第一个项目,但不适用于多个项目。我如何得到最好的帮助
Public Sub saveItemListview(lstview As ListView)
Try
con = New SqlConnection(My.Settings.StockConnectionString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
sql = "insert into salestb values(@items,@quantity,@price)"
Dim cmd As SqlCommand = New SqlCommand(sql, con)
For Each item As ListViewItem In lstview.Items
cmd.Parameters.AddWithValue("@Items", item.Text.ToString.Trim)
cmd.Parameters.AddWithValue("@quantity", item.SubItems(1).Text.ToString.Trim)
cmd.Parameters.AddWithValue("@Price", item.SubItems(2).Text.ToString.Trim)
cmd.ExecuteNonQuery()
cmd.Dispose()
Next
MsgBox("Save Successsfully")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Sub saveItemListview(lstview As ListView)
Try
con = New SqlConnection(My.Settings.StockConnectionString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
sql = "insert into salestb values(@items,@quantity,@price)"
Dim cmd As SqlCommand = New SqlCommand(sql, con)
For Each item As ListViewItem In lstview.Items
cmd.Parameters.AddWithValue("@Items", item.Text.ToString.Trim)
cmd.Parameters.AddWithValue("@quantity", item.SubItems(1).Text.ToString.Trim)
cmd.Parameters.AddWithValue("@Price", item.SubItems(2).Text.ToString.Trim)
cmd.ExecuteNonQuery()
cmd.Dispose()
Next
MsgBox("Save Successsfully")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
如果我尝试了多个项目,则会显示错误消息:
变量名“ @items”已声明。变量名必须 在查询批处理或存储过程中始终是唯一的。
答案 0 :(得分:0)
Public Sub saveItemListview(lstview As ListView)
Try
con = New SqlConnection(My.Settings.StockConnectionString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
sql = "insert into salestb values(@items,@quantity,@price)"
Dim cmd As SqlCommand = New SqlCommand(sql, con)
For Each item As ListViewItem In lstview.Items
cmd.Parameters.AddWithValue("@Items", item.Text.ToString.Trim)
cmd.Parameters.AddWithValue("@quantity", item.SubItems(1).Text.ToString.Trim)
cmd.Parameters.AddWithValue("@Price", item.SubItems(2).Text.ToString.Trim)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd.Parameter.clear()
Next
MsgBox("Save Successsfully")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub