2015年4月17日金曜日

DataGridViewのチェックボックス列を編集不可のグレー表示

.NetのDataGridViewの行をReadOnlyにするとチェックボックス列も編集不可になるけど、
見た目では判らない。

見た目で判るように灰色表示できないか探したところ
以下の方法に行き着いた。

はじめ、ControlPaint.DrawCheckBoxを使ってて
チェック無しはInactiveで出来るけど、チェックありが出来ない!

と困ってたのだが、
ControlPaint.DrawMixedCheckBoxに変えたらあっさり出来た。


ControlPaint.DrawCheckBoxで両方出来るように
しといてくれればいいのに。。


Private Sub dgv_CellPainting(sender As System.Object, 
                             e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) 
                             Handles dgv.CellPainting
    Dim selected As Boolean

    If e.RowIndex >= 0 and e.ColumnIndex >= 0 Then

        'チェックボックス列であれば
        If TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewCheckBoxColumn Then

            '変更不可行であれば
            If dgv.Rows(e.RowIndex).ReadOnly Then

                selected = CBool(e.State And DataGridViewElementStates.Selected)

                '描画する領域
                e.PaintBackground(e.CellBounds, selected)
                Dim rect As Rectangle = e.CellBounds
                rect.Width = 16
                rect.Height = 16
                rect.Offset((e.CellBounds.Width - 16) \ 2, rect.Height \ 2 - 8)

                '状態によって、チェックボックスを描画する
                If dgv.Rows(e.RowIndex).Cells("FLG").Value.ToString = "1" Then
                    ControlPaint.DrawMixedCheckBox(e.Graphics, rect, ButtonState.Checked)
                Else
                    ControlPaint.DrawMixedCheckBox(e.Graphics, rect, ButtonState.Inactive)
                End If

                e.Handled = True
            End If
        End If
    End If

End Sub