在选中或取消选中时更改DataGridViewCheckBoxColumn的BackColor

时间:2019-01-29 00:49:21

标签: .net vb.net winforms datagridview

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-运行此项目,然后取消选中复选框之一。

我想立即单击复选框立即看到红色。

1 个答案:

答案 0 :(得分:0)

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

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

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

然后您可以拥有类似的内容:

enter image description here

在示例中,我将False显示为Red,将TrueDbNull.Value显示为While。您可以根据需要更改逻辑。要获得在动画中看到的内容,请将DataGridView放在表单上并粘贴以下代码:

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

注意

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