如何在 CellValueChanged 事件后向 DataGridView 中的已编辑单元格添加红色边框

How to add red border to edited cell in DataGridView after CellValueChanged Event

我有一个 CellValueChanged 事件,在该事件中我将任何更新的记录添加到审计中 table,我想在此事件中将单元格边框更改为红色以指示单元格已更新:

Private Sub PL_DGV_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles PL_DGV.CellValueChanged
        If isLoaded Then
            Dim grid_row As DataRow = Me.DataSet.PL.Rows(e.RowIndex)

            Dim Column1 = Variable1
            Dim Column2 = grid_row.Item("Column2").ToString().Trim()
            Dim Column3 = grid_row.Item("Column3").ToString().Trim()

            Dim Updated_column_name = Me.DataSet.PL.Columns(e.ColumnIndex).ColumnName
            Dim Updated_value = grid_row.Item(Updated_column_name).ToString()

            Dim row As DataRow = Me.DataSet.PL_ChangesLog.NewRow()
            row("Column1") = Column1
            row("Column2") = Column2
            row("Column3") = Column3
            row("Column4") = Updated_column_name
            row("Column5") = Updated_value
            row("timestamp") = DateTime.Now()
            row("username") = Environment.UserName()

            Me.DataSet.PL_ChangesLog.Rows.Add(row)

            Dim new_style = New DataGridViewCellStyle

            unsaved_changes = True
        End If
End Sub

此外,保存更改后,这些单元格需要再次移除边框以恢复默认值。这将通过按钮或在表单关闭且用户选择“是”时发生:

Private Sub PLC_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If unsaved_changes Then
            Dim result = MsgBox("There are unsaved changes within the grid - would you like to save changes?", MessageBoxButtons.YesNoCancel)
            If result = DialogResult.Yes Then

            ElseIf result = DialogResult.Cancel Then
                e.Cancel = True
            End If
        End If
End Sub

是否可以在 CellValueChanged 事件中完成,还是应该根据更新的单元格索引作为单独的函数完成?

参考这个 link How do you draw a border around a DataGridView cell while it's being edited?

或者您可以试试这个,但需要改进代码

 Dim rec As New Drawing.Rectangle

            rec = DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False)

            DataGridView1.CreateGraphics.DrawRectangle(New Pen(Color.Red, 2), CInt(rec.X), CInt(rec.Y), CInt(rec.Width - 2), CInt(rec.Height - 2))

            DataGridView1.EditingControl.BackColor = Color.Red

我还没有想出如何正确地在单元格周围绘制一个矩形,但在与要求提供者进一步讨论后,将其中编辑了单元格的行设置为粗体。

通过以下代码实现:

    Dim DGV_row As DataGridViewRow = PL_DGV.Rows(e.RowIndex)
    Dim new_style As New DataGridViewCellStyle With {
        .Font = New System.Drawing.Font("Segoe UI", 9, FontStyle.Bold)
    }
    DGV_row.DefaultCellStyle = new_style