如何在cellvaluechange事件后为DataGridView中编辑的单元格添加红色边框 &g



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

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

而且,一旦保存了更改,这些单元格需要将其边框再次移回默认值。这可以通过按钮发生,也可以在窗体关闭时用户选择"Yes":

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

是否有可能在cellvaluechange事件内完成,或者应该根据更新的单元格索引作为单独的函数完成?

参考此链接如何在编辑DataGridView单元格时绘制边框?

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

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

最新更新