【问题标题】:VB.net DataGridview: Represent Boolean column using imagesVB.net DataGridview:使用图像表示布尔列
【发布时间】:2015-07-11 00:22:27
【问题描述】:

我有一个 DataGridView dgv 显示底层 DataView dv 的内容,我用它来过滤行条目。 (dgv.DataSource = dv)

DataView 中的两列是布尔类型,并显示为 VB 的默认复选框格式,但是,我希望它们分别显示为红色和绿色的正方形(或矩形),分别代表 False 和 True。

我知道对于具有DataGridViewImageColumn 类型列的 DataGridView,我可以简单地生成一个图像并用类似的东西显示它:

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 以包含图像,但后来我不知道如何按该列的值进行过滤。因此我希望有一些方法可以在不改变底层结构的情况下简单地改变可视化。

【问题讨论】:

  • 可以在视图加载后重绘单元格吗?
  • 是否可以在创建datagridview并填写信息后以这种方式更改列?在不破坏底层数据视图的链接的情况下...

标签: vb.net image datagridview


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    对于简单的颜色填充操作,不需要使用位图。只需订阅 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
    

    欲了解更多信息,请参阅:Customizing the Windows Forms DataGridView Control

    【讨论】:

    • 您和 Fabio 的解决方案似乎都符合我的要求,我可能会先尝试这两种方法,然后再决定哪一种更合适。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多