【VB.NET】DataGridViewのセル選択時に黒い枠線を表示する方法

画面イメージ

選択状態のセルに黒い枠線を描画

VB
    Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting

        If e.ColumnIndex < 0 Then Return
        If e.RowIndex < 0 Then Return

        '背景を描画する場合
        If (e.PaintParts And DataGridViewPaintParts.Background) = DataGridViewPaintParts.Background Then

            'セルの境界線の範囲を白(セルの背景色)で塗りつぶす
            e.Graphics.FillRectangle(New SolidBrush(e.CellStyle.BackColor), e.CellBounds)

            '選択セルの背景を描画する場合、かつ、セルが選択されている状態の場合
            If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = DataGridViewPaintParts.SelectionBackground AndAlso
               (e.State And DataGridViewElementStates.Selected) = DataGridViewElementStates.Selected Then

                '黒で長方形を描画する
                e.Graphics.DrawRectangle(New Pen(Color.Black, 2),
                                         e.CellBounds.X + 1,
                                         e.CellBounds.Y + 1,
                                         e.CellBounds.Width - 3,
                                         e.CellBounds.Height - 3)
            End If

            Dim paintParts As DataGridViewPaintParts = e.PaintParts And Not DataGridViewPaintParts.Background
            e.Paint(e.ClipBounds, paintParts)
            e.Handled = True
        End If

    End Sub

動作確認用コード

VB
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      
        Dim dt As New DataTable
        With dt
            .Columns.Add("Col1", GetType(String))
            .Columns.Add("Col2", GetType(String))
            .Rows.Add("A001", "B001")
            .Rows.Add("A002", "B002")
        End With

        With DataGridView1
            .DataSource = dt
            .AllowUserToAddRows = False
            .RowHeadersVisible = False
            .DefaultCellStyle.SelectionForeColor = Color.Black
            .DefaultCellStyle.SelectionBackColor = Color.White
        End With
        
    End Sub

コメント

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