Save multiple times by doing a LOOP depending on the number of checked checkboxes on a datagridview VB.NET 2010
I have a datagridview with checkboxes in the first column and I want to do a loop on saving the serialnumber(s) when the users decides to check a number of checkboxes ...
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
the problem with this code is that it only inserts the serial number of the LAST checked checkbox and the number of entries of it depends on the number of checked checkbox ...
for example ... if I checked t开发者_运维技巧he rows with the serialnumber 123 and 55652341, first the row with the serial number 123 then second 55652341, only 55652341 appears in the database and it is entered twice(twice because two checkboxes are checked) ...
hope I made it clear and someone could help me ...
You need to update the SerialNumber variable inside the loop where you iterate through the rows.
serialnumber = row.Cells("SerialNumber").Value
As a side note, your loop could be more efficient if you open the connection before the loop, and close it afterwards. Opening and closing it for every iteration is going to slow things down.
精彩评论