注意:ここで紹介しているDataGridは、System.Windows.Forms名前空間のDataGrid(Windowsフォーム)です。System.Web.UI.WebControls名前空間のDataGrid(Webフォーム)ではありません。
DataGridColumnStyle.PaintメソッドをオーバーライドしたDataGridColumnStyleからの派生クラスを作成することにより、セルの色を自由に変えることが出来るようになります。
まずは次のようなクラスを作成します。このPaintメソッド内でどのようなセルにどのような色をつけるか指定します。この例ではDataGridTextBoxColumnから派生したMyDataGridTextBoxColumnクラスを作成し、値が"0"のセルを前景色が白、背景色が黒で表示するようにしています。
'DataGridTextBoxColumnを継承してクラスを作成 Public Class MyDataGridTextBoxColumn Inherits DataGridTextBoxColumn 'Paintメソッドをオーバーライドする 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 _ ) 'セルの値を取得する Dim cellValue As Object = _ Me.GetColumnValueAtRow(source, rowNum) If Not (cellValue Is Nothing) AndAlso _ Not (cellValue Is DBNull.Value) Then '値が"0"のセルの前景色と背景色を変える If CType(cellValue, String) = "0" Then foreBrush = New SolidBrush(Color.White) backBrush = New SolidBrush(Color.Black) End If End If '基本クラスのPaintメソッドを呼び出す MyBase.Paint(g, bounds, source, rowNum, _ backBrush, foreBrush, alignToRight) End Sub End Class
//DataGridTextBoxColumnを継承してクラスを作成 public class MyDataGridTextBoxColumn : DataGridTextBoxColumn { //Paintメソッドをオーバーライドする protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight) { //セルの値を取得する object cellValue = this.GetColumnValueAtRow(source, rowNum); if (cellValue != null) { //値が"0"のセルの前景色と背景色を変える if ((string) cellValue == "0" && cellValue != DBNull.Value) { foreBrush = new SolidBrush(Color.White); backBrush = new SolidBrush(Color.Black); } } //基本クラスのPaintメソッドを呼び出す base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); } }
次にセルの色を変えたい列にこの列スタイルを使うようにします。列スタイルの説明は省かれていますので、分からないという方はこちらをご覧ください。以下の例では、データソースが"Column1"という名前のDataColumnがある"DataTable1"という名前のDataTableであることを前提にしています。
'新しいDataGridTableStyleの作成 Dim ts As New DataGridTableStyle() 'マップ名を指定する ts.MappingName = "DataTable1" '列スタイルにMyDataGridTextBoxColumnを使う Dim cs As MyDataGridTextBoxColumn cs = New MyDataGridTextBoxColumn() 'マップ名を指定する cs.MappingName = "Column1" 'DataGridTableStyleに追加する ts.GridColumnStyles.Add(cs) 'テーブルスタイルをDataGridに追加する DataGrid1.TableStyles.Add(ts)
//新しいDataGridTableStyleの作成 DataGridTableStyle ts = new DataGridTableStyle(); //マップ名を指定する ts.MappingName = "DataTable1"; //列スタイルにMyDataGridTextBoxColumnを使う MyDataGridTextBoxColumn cs; cs = new MyDataGridTextBoxColumn(); //マップ名を指定する cs.MappingName = "Column3"; //DataGridTableStyleに追加する ts.GridColumnStyles.Add(cs); //テーブルスタイルをDataGridに追加する DataGrid1.TableStyles.Add(ts);
補足:.NET Framework 1.1ではDataGridのDataSourceプロパティをnull(VB.NETではNothing)に設定しても、選択されたセルがクリアされないという問題があるようです。詳しくは、サポート技術情報をご覧ください。
注意:この記事では、基本的な事柄の説明が省略されているかもしれません。初心者の方は、特に以下の点にご注意ください。