Reputation: 136
I have a DataGridView dgv
showing the content of an underlying DataView dv
, which I use for filtering the row entries. (dgv.DataSource = dv
)
Two of the columns in the DataView are Boolean types and show up as the default checkbox formatting of VB, however, I would like them to show as squares (or rectangles) in colors red and green for False and True respectively.
I know that for a DataGridView with a column of the type DataGridViewImageColumn
I could simply generate an image and show it with something similar to this:
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
But I have no Idea how to do something similar with a column originating from a linked DataView; much less when the column is not even an image column.
I considered changing the underlying DataView to contain an image, but then I don't know how I would filter by the value of that column. Thus I hope there is some way to simply change the visualization without changing the underlying structure.
Upvotes: 1
Views: 1797
Reputation: 11801
For a simple color fill operation, there is no need to use a bitmap. Just subscribe to the CellPainting event on the DatagridView.
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
For more information, see: Customizing the Windows Forms DataGridView Control
Upvotes: 1
Reputation: 32455
Use Cell Formatting
event handler
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
Upvotes: 1