SQL Server查询参数用于将数据表复制到另一个表单ListView VB.net
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server查询参数用于将数据表复制到另一个表单ListView VB.net相关的知识,希望对你有一定的参考价值。
我正在使用VB.net 2013和SQL Server Express。我想将列表视图中显示的表中的数据复制到临时表。但是我收到了一个错误:
运算符'&'未定义类型'String'和'System.Windows.Forms.ListViewItem.ListViewSubItem'
什么是正确的参数?
我的代码看起来像这样
For Each itm As ListViewItem In ListViewMasterBiaya.CheckedItems
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya WHERE NoKode='" & ListViewMasterBiaya.SelectedItems(0).SubItems(0) & "'"
CMD = New SqlCommand(SIMPAN, CONN)
CMD.ExecuteNonQuery()
Next
End Sub
我还包括如下图像,当我检查它时,数据也将复制到临时表
答案
在线评论和解释。继LarsTech评论之后。
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya (Column1Name, Column2Name) Values (@Column1, @Column2);"
'The Using...End Using blocks ensure that your ADO objects are closed and
'disposed event if there is an error
Using cn As New SqlConnection("Your connection string")
'The command and parameters only need to be declared once
'outside the loop, only the value of the parameters change
Using cmd As New SqlCommand(SIMPAN, cn)
cmd.Parameters.Add("@Column1", SqlDbType.Int)
cmd.Parameters.Add("@Column2", SqlDbType.VarChar)
'Open the connection at the last possible moment
cn.Open()
For Each itm As ListViewItem In ListViewMasterBiaya.CheckedItems
cmd.Parameters("@Column1").Value = itm.SubItems(0).Text
cmd.Parameters("@Column2").Value = itm.SubItems(1).Text
cmd.ExecuteNonQuery()
Next
End Using
End Using
编辑使用事件ListView.ItemChecked
Private Sub ListViewMasterBiaya_ItemChecked(sender As Object, e As ItemCheckedEventArgs) Handles ListViewMasterBiaya.ItemChecked
'e.Item returns the ListViewItem that changed its check
If e.Item.Checked = True Then
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya (Column1Name, Column2Name) Values (@Column1, @Column2);"
'The Using...End Using blocks ensure that your ADO objects are closed and
'disposed event if there is an error
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand(SIMPAN, cn)
cmd.Parameters.Add("@Column1", SqlDbType.Int).Value = e.Item.SubItems(0)
cmd.Parameters.Add("@Column2", SqlDbType.VarChar).Value = e.Item.SubItems(1)
'Open the connection at the last possible moment
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End If
End Sub
以上是关于SQL Server查询参数用于将数据表复制到另一个表单ListView VB.net的主要内容,如果未能解决你的问题,请参考以下文章
将 SQL Server Express 数据库复制到另一台计算机
按计划将SQL Server数据从一台服务器复制到另一台服务器