[英]VB.net DataGridview: Represent Boolean column using images
我有一个DataGridView dgv
显示基础DataView dv
的内容,我用它来过滤行条目。 ( dgv.DataSource = dv
)
DataView中的两列是布尔类型,显示为VB的默认复选框格式,但是,我希望它们分别以False和True的形式显示为红色和绿色的正方形(或矩形)。
我知道,对于具有类型为DataGridViewImageColumn的列的DataGridViewImageColumn
我可以简单地生成图像并用类似于以下内容的方式显示它:
bmp = New Bitmap(20, 10)
Using g As Graphics = Graphics.FromImage(bmp)
If VarIsValid Then
g.FillRectangle(Brushes.GreenYellow, 0, 0, bmp.Width - 1, bmp.Height - 1)
Else
g.FillRectangle(Brushes.Red, 0, 0, bmp.Width - 1, bmp.Height - 1)
End If
g.DrawRectangle(Pens.Black, 0, 0, bmp.Width - 1, bmp.Height - 1)
End Using
row.Cells("VarIsValid").Value = bmp
但是我不知道如何对源自链接的DataView的列执行类似的操作; 如果该列甚至不是图像列,则更少。
我考虑过将基础DataView更改为包含图像,但是后来我不知道如何根据该列的值进行过滤。 因此,我希望有某种方法可以简单地更改可视化效果而不更改底层结构。
使用Cell Formatting
事件处理程序
Private Sub dgv_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv.CellFormatting
If e.RowIndex < 0 OrElse e.ColumnIndex < 0 Then Exit Sub
'You can check that column is right by ColumnIndex
'I prefer using a name of the DataGridViewColumn,
'because indexes can be changed while developing
If Me.dgv.Columns(e.ColumnIndex).Name.Equals("PredefinedColumnName") = True Then
If CBool(e.Value) = True Then
e.Value = My.Resources.GreenSquare 'image saved in the resources
Else
e.Value = My.Resources.RedSquare
End If
End If
End Sub
对于简单的颜色填充操作,无需使用位图。 只需在DatagridView上订阅CellPainting事件。
Private Sub dgv1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles dgv1.CellPainting
Const checkboxColumnIndex As Int32 = 0 ' set this to the needed column index
If e.ColumnIndex = checkboxColumnIndex AndAlso e.RowIndex >= 0 Then
Dim br As Brush
If CBool(e.Value) Then
br = Brushes.GreenYellow
Else
br = Brushes.Red
End If
e.Graphics.FillRectangle(br, e.CellBounds)
e.Paint(e.ClipBounds, DataGridViewPaintParts.Border)
e.Handled = True
End If
End Sub
有关更多信息,请参见: 自定义Windows窗体DataGridView控件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.