【VB.NET】DataGridViewのセルの値に応じた書式設定を行う

画面イメージ

セルの値に応じて背景色を変更する

VB
    Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

        If DataGridView1.Columns(e.ColumnIndex).Name <> "Stock" Then Return

        If e.Value < 0 Then
            e.CellStyle.BackColor = Color.LightSalmon
        ElseIf e.Value > 100 Then
            e.CellStyle.BackColor = Color.LightGreen
        Else
            e.CellStyle.BackColor = Color.White
        End If

    End Sub

動作確認用コード

VB
Public G_dtStock As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    With G_dtStock
        .Columns.Add("ProductID", GetType(String))
        .Columns.Add("Stock", GetType(String))
        .Rows.Add("C1", "10")
        .Rows.Add("C2", "150")
        .Rows.Add("C3", "-90")
        .Rows.Add("C4", "30")
        .Rows.Add("C5", "120")

    End With

    With DataGridView1
        .DataSource = G_dtStock
        .AllowUserToAddRows = False
    End With

End Sub

コメント

タイトルとURLをコピーしました