MySQL Question

Save Datagridview if it is Checked by CheckboxColumn

Hello Everyone Good Afternoon,

I have an Object in a form and they are

Datagridview1
and a Save
Button
the
Datagridview1
will populate data from my Database on
Form_Load
and the Data will show with a Corresponding Checkbox. Like the Image below

enter image description here

and If you here is the code for that

Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()

With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub


and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)

Here is my code but its not working. :(

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()

Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn


Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value


comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next

conn.Close()
End Sub


TYSM For future help

Answer

Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1

Dim name As String
        For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
           If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
            name = Me.DataGridView1.Rows(i).Cells(1).Value


            comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
            comm.ExecuteNonQuery()
           End If
        Next
Comments