首页 > 解决方案 > 在选中或取消选中时更改 DataGridViewCheckBoxColumn 的背景颜色

问题描述

1-在Form1上添加一个DataGridView,命名为DataGridView1。

2-将以下代码复制并粘贴到后面的代码中。

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim myColumn As New DataGridViewCheckBoxColumn With {.ValueType = GetType(Boolean), .Name = "Option", .HeaderText = "Option"}
    myColumn.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.Transparent
    DataGridView1.Columns.Add(myColumn)
    For ii As Integer = 1 To 2
        DataGridView1.Rows.Add({True})
    Next
End Sub
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If DataGridView1.Columns(e.ColumnIndex).Name = "Option" AndAlso DataGridView1.Rows(e.RowIndex).IsNewRow = False Then
        If e.Value = False Then
            e.CellStyle.BackColor = System.Drawing.Color.Red
            'I tried following codes but they are not
            'DataGridView1.Refresh()
            'DataGridView1.Update()
        End If
    End If
End Sub
End Class

3- 运行此项目并取消选中其中一个复选框。

我希望在单击 CheckBox 后立即看到红色。

标签: .netvb.netwinformsdatagridview

解决方案


考虑以下几点以实现在检查时更改单元格的背景颜色,并删除选择突出显示:

  1. 要将复选框值推送到单元格,您需要处理CellContentClickCellContentDoubleClick使用DataGridView.CommitEdit(DataGridViewDataErrorContexts)方法来提交对单元格值的更改。如果不这样做,在您结束编辑之前,该值不会推送到单元格。

  2. 要使选择背景颜色不可见,您需要将SelectionBackColor单元格设置为与 相同的颜色BackColor

然后你可以有这样的东西:

在此处输入图像描述

在示例中,我显示FalseRed和。您可以根据需要更改逻辑。要实现您在动画中看到的效果,请将 a 拖放到表单上并粘贴以下代码:TrueDbNull.ValueWhileDataGridView

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim table = New DataTable()
    table.Columns.Add("C1", GetType(Boolean))
    table.Columns.Add("C2", GetType(String))
    table.Rows.Add(True, "A")
    table.Rows.Add(False, "B")
    DataGridView1.DataSource = table
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object,
    e As DataGridViewCellEventArgs) _
    Handles DataGridView1.CellContentClick, DataGridView1.CellContentDoubleClick

    If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 Then
        DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        DataGridView1.InvalidateCell(e.ColumnIndex, e.RowIndex)
    End If
End Sub
Private Sub DataGridView1_CellPainting(sender As Object,
    e As DataGridViewCellPaintingEventArgs) _
    Handles DataGridView1.CellPainting

    If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 Then
        If TypeOf (e.Value) Is Boolean AndAlso e.Value = False Then
            e.CellStyle.BackColor = Color.Red
        Else
            e.CellStyle.BackColor = Color.White
        End If
    End If
    e.CellStyle.SelectionBackColor = e.CellStyle.BackColor
    e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor
End Sub

笔记

您还可以使用此处描述的解决方案:


推荐阅读