我在第一列中有一个带有复选框的datagridview,当用户决定检查多个复选框时,我想在保存序列号时进行循环...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim serialnumber As String = DataGridView1.CurrentRow.Cells("SerialNumber").Value
Dim siteid As String = Main.StatusBar1.Panels(2).Text
Dim connection As New SqlConnection
Dim cmd As New SqlCommand
connection.ConnectionString = "Data Source =TOBZ-PC; Initial Catalog =Glowb; Integrated Security =SSPI;"
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(Column1.Name).Value = True Then
connection.Open()
cmd.Connection = connection
cmd.CommandText = " insert into [equipment request](serialnumber, siteid) values('" & serialnumber & "', '" & siteid & "') "
cmd.ExecuteNonQuery()
connection.Close()
End If
Next
End Sub
此代码的问题在于它只插入了LAST checked复选框的序列号,其条目数取决于复选复选框的数量......
例如......如果我使用序列号123和55652341检查行,首先是序列号为123的行,然后是第二行55652341,数据库中只出现55652341并输入两次(两次因为选中了两个复选框) )...
希望我说清楚,有人可以帮助我......
答案 0 :(得分:3)
您需要在遍历行的循环内更新SerialNumber变量。
serialnumber = row.Cells("SerialNumber").Value
作为旁注,如果在循环之前打开连接,并且之后关闭它,则循环可能更有效。每次迭代打开和关闭它都会减慢速度。