Windows フォーム DataGridView コントロールでのセルのスタイル

  • やりたいこと

列A 列B 列C 列D
       
       
       
       

  • デザイナで作成すると

列A 列B 列C 列D
       
       
       
       

通常、DataGridViewで一行おきに背景色を変える場合は、AlternatingRowsDefaultCellStyle プロパティでBackColor を変更すれば反映される。

  • 方法 : Windows フォーム DataGridView コントロールに交互の行のスタイルを設定する

http://msdn2.microsoft.com/ja-JP/library/txth0a6h.aspx

ここで終わるなら話は簡単。

さらに特定の列の背景色を変更したいというと、上記のようになる。
列単位で背景色を指定したいので、DataGridViewColumnのDefaultCellStyle.BackColorを設定した。これで列単位に背景色が変更される・・・というわけではない。
AlternatingRowsDefaultCellStyle に該当する行は、DataGridViewColumn.DefaultCellStyleスタイルが無視されてしまう。

原因を調べてみたら、DataGridViewの書式設定に一定の継承関係の理解が必要なようだ。

http://msdn2.microsoft.com/ja-JP/library/1yef90x0.aspx

継承の順番からいくと、一番根っこが
DataGridView.DefaultCellStyle

DataGridViewColumn.DefaultCellStyle

DataGridView.RowsDefaultCellStyle

DataGridView.AlternationgRows.DefaultCellStyle

DataGridViewRow.DefaultCellStyle

DataGridViewCell.Style

DataGridViewCell.InheritedStyle

という順番で、最後のヤツが一番優先されるようだ。

詳しくはこの図で(http://msdn2.microsoft.com/ja-JP/library/1yef90x0.Local_501028840_datagridviewcells1.gif)