WindowsFormのDataGridには特定のセルまたは行に色を付ける
機能はありません。
そこでDataGridColumnStyle.Paintメソッドをオーバーライドした
DataGridColumnStyleからの派生クラスを作成することにより、
特定のセルの色を自由に変えることが出来るようになります。
まずは下記のクラスを作ります。
-----------------
Public Class MyDataGridTextBoxColumn
Inherits DataGridTextBoxColumn
Public Event CellPaint( _
ByVal ColumnMappingName As String, _
ByVal rowNum As Integer, _
ByRef backBrush As Brush, _
ByRef foreBrush As Brush _
)
Protected Overloads Overrides Sub Paint( _
ByVal g As Graphics, _
ByVal bounds As Rectangle, _
ByVal source As CurrencyManager, _
ByVal rowNum As Integer, _
ByVal backBrush As Brush, _
ByVal foreBrush As Brush, _
ByVal alignToRight As Boolean _
)
RaiseEvent CellPaint(Me.MappingName, rowNum, backBrush, foreBrush)
MyBase.Paint(g, bounds, source, rowNum, _
backBrush, foreBrush, alignToRight)
End Sub
End Class
-----------------
次に色を付けたいDataGridが存在するクラスに下記のメソッドを
書きます。
ここで色の指定を行います。
また、ここで条件文などを書いてあげると条件に沿った形で
色を付けてくれます。
------------------
Private Sub gcsPaint( _
ByVal ColumnMappingName As String, _
ByVal rowNum As Integer, _
ByRef backBrush As Brush, _
ByRef foreBrush As Brush _
)
backBrush = Brushes.Red
End Sub
-----------------
この二つの部品があれば特定のセル、行に色を指定してあげることが
出来ますが、一つ注意点があります。
上記のPaintメソッドはGridColumnStyleがDataGridTableStyleに追加され
た時に発動します。
ですので色を追加したい時にはコード上でわざわざGridColumnStyle
を追加してやらなければなりませんが、それは色を指定したい列だけ
で大丈夫です。
GridColumnStyleを追加する時は下記のように
「AddHandler cs.CellPaint, AddressOf gcsPaint」
を書いてあげる必要があります。
------------------
Dim ts As New DataGridTableStyle
Dim cs As MyDataGridTextBoxColumn
cs = New MyDataGridTextBoxColumn
cs.MappingName = "あいろべっくす"
AddHandler cs.CellPaint, AddressOf gcsPaint ←これ
'追加
ts.GridColumnStyles.Add(cs)
DataGrid1.TableStyles.Add(ts)
------------------
これでDataGridの特定のセルに色を指定してあげることが出来ます。
特定のセルに色を付けるためには「gcsPaint」メソッドで条件を入れてあ
げる必要があるので忘れずに。