如何使用复选框更新特定行?

时间:2018-11-21 06:44:29

标签: vb.net

这是我尝试过的。这仅适用于复选框值,并且所有显示的数据都会更新。

 Public Sub updateDGV()



    Dim id As String
    Dim cb As String
    Dim time As String
    Dim str As String
    Dim mycon As New SqlConnection(ConString)
    Try
        mycon.Open()
        For Each row As DataGridViewRow In dgv.Rows
            row.Cells(22).Value = Date.Now.ToString("MM/dd/yyyy HH:mm:ss tt")
            id = row.Cells(0).Value.ToString
            cb = row.Cells(1).Value.ToString
            time = row.Cells(22).Value.ToString
            str = "UPDATE GuardMonitoring SET EmploymentStatus =@EmpStat, 
           ModifiedBy =@ModifiedBy, ModifyDate =@ModifyDate WHERE 
            (Employee_Id =@EmpId)"


            Dim cmd As SqlCommand = New SqlCommand(str, mycon)
            cmd.Parameters.AddWithValue("@EmpId", SqlDbType.VarChar).Value = id
            cmd.Parameters.AddWithValue("@EmpStat", SqlDbType.VarChar).Value = cb
            cmd.Parameters.AddWithValue("@ModifiedBy", SqlDbType.VarChar).Value = UserPass.txtfull2.Text
            cmd.Parameters.AddWithValue("@ModifyDate", SqlDbType.VarChar).Value = time
            cmd.ExecuteNonQuery()

        Next
        mycon.Close()
    Catch ex As Exception
        showmsg.ForeColor = Color.LightCoral
        showmsg.Text = "Rows not found!"
        MsgBox(ex.Message)
    End Try

End Sub

预期输出:仅在更改复选框的特定值时更新。

1 个答案:

答案 0 :(得分:0)

您是说只想更新复选框已打开的行吗? 如果是这样,则可以通过复选框单元格的值来确定。

例如,像这样。

 Public Sub updateDGV()



    Dim id As String
    Dim cb As String
    Dim time As String
    Dim str As String
    Dim mycon As New SqlConnection(ConString)
    Try
        mycon.Open()
        For Each row As DataGridViewRow In dgv.Rows
            If Convert.ToBoolean(row.Cells("your checkbox column name").Value) Then
                row.Cells(22).Value = Date.Now.ToString("MM/dd/yyyy HH:mm:ss tt")
                id = row.Cells(0).Value.ToString
                cb = row.Cells(1).Value.ToString
                time = row.Cells(22).Value.ToString
                str = "UPDATE GuardMonitoring SET EmploymentStatus =@EmpStat, 
               ModifiedBy =@ModifiedBy, ModifyDate =@ModifyDate WHERE 
                (Employee_Id =@EmpId)"


                Dim cmd As SqlCommand = New SqlCommand(str, mycon)
                cmd.Parameters.AddWithValue("@EmpId", SqlDbType.VarChar).Value = id
                cmd.Parameters.AddWithValue("@EmpStat", SqlDbType.VarChar).Value = cb
                cmd.Parameters.AddWithValue("@ModifiedBy", SqlDbType.VarChar).Value = UserPass.txtfull2.Text
                cmd.Parameters.AddWithValue("@ModifyDate", SqlDbType.VarChar).Value = time
                cmd.ExecuteNonQuery()
            End If

        Next
        mycon.Close()
    Catch ex As Exception
        showmsg.ForeColor = Color.LightCoral
        showmsg.Text = "Rows not found!"
        MsgBox(ex.Message)
    End Try

End Sub