.net - 在选中或取消选中时更改 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 后立即看到红色。
解决方案
考虑以下几点以实现在检查时更改单元格的背景颜色,并删除选择突出显示:
要将复选框值推送到单元格,您需要处理
CellContentClick
和CellContentDoubleClick
使用DataGridView.CommitEdit(DataGridViewDataErrorContexts)
方法来提交对单元格值的更改。如果不这样做,在您结束编辑之前,该值不会推送到单元格。要使选择背景颜色不可见,您需要将
SelectionBackColor
单元格设置为与 相同的颜色BackColor
。
然后你可以有这样的东西:
在示例中,我显示False
为Red
和。您可以根据需要更改逻辑。要实现您在动画中看到的效果,请将 a 拖放到表单上并粘贴以下代码:True
DbNull.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
笔记
您还可以使用此处描述的解决方案:
推荐阅读
- sql - 在嵌套选择查询中按条件分组后加入
- mysql - 查找用户输入的值或对行值求和
- javascript - 如何使用 django-channels 2 处理消息?
- python - 我有以下结构的列表,需要从中返回数据
- heroku - 在 Heroku 上配置域不起作用
- aframe - 自定义标记不显示任何内容
- python - TypeError:“分页”对象在 Flask 中不可迭代
- angular - Angular:当可以下载n个项目时如何设置下载微调器
- linux - libpcap是否使用了linux的流量控制层?
- python-3.x - 无法使用 paramiko sudo su