DataGridView 条件付き書式の実装テクニック(サンプルあり)
📋 目次(クリックで展開)
本記事では、業務システムなどでよく使われる、DataGridView の条件付き書式の実装方法を紹介します。
条件付き書式について
条件付き書式は、値に応じてセルや行の背景色・文字色などを変えることで、ユーザーに重要な情報を視覚的に伝えるためのテクニックです。
主な活用例
- 売上が一定金額を超えたら背景を緑でハイライトする
- エラーがあるデータは赤く強調する
- 期限切れの行はグレーで配色する
実装方法:CellFormatting イベントを使う
DataGridView の CellFormatting イベントは、セルが描画される直前に呼び出されます。このイベント内で条件を判定し、スタイルを動的に変更します。
例①:数値が 100 を超えたら背景を緑にする
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e){ if (dataGridView1.Columns[e.ColumnIndex].Name == "売上") { if (e.Value != null && int.TryParse(e.Value.ToString(), out int value)) { if (value > 100) { e.CellStyle.BackColor = Color.LightGreen; e.CellStyle.ForeColor = Color.Black; e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold); } } }}例②:エラー行全体を赤くする
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e){ if (dataGridView1.Columns[e.ColumnIndex].Name == "ステータス") { var row = dataGridView1.Rows[e.RowIndex]; if (row.Cells["ステータス"].Value?.ToString() == "エラー") { row.DefaultCellStyle.BackColor = Color.LightCoral; row.DefaultCellStyle.ForeColor = Color.White; } }}実行結果
↓ 例①と②を踏まえた実行結果です。

サンプルアプリケーション
DataGridView_ConditionalFormatting_CS.zip
※ サンプルアプリケーションのターゲットフレームワークは .NET 9 です。
💬 コメント