ssCAROのブログ

色んなとこで見つけたプログラムのメモ置き場っぽい

DataGridViewでセルを選択させない

DBから取得した値をDataGridViewに表示するだけで選択をさせない。
DBから取得した値で行を色分けもする。
選択したときの色を、行の背景色と同じにすれば良い。

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
   '固定行を非表示にする
    DataGridView1.RowHeadersVisible = False
   '行選択にする
    DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
   '複数行選択出来ないようにする
    DataGridView1.MultiSelect = False
   'ユーザーからの行削除を出来ないようにする
    DataGridView1.AllowUserToDeleteRows = False
   'ユーザーからの行追加を出来ないようにする
    DataGridView1.AllowUserToAddRows = False
   'ユーザーからの行幅変更を出来ないようにする
    DataGridView1.AllowUserToResizeRows = False
   '読み取り専用
    DataGridView1.ReadOnly = True
End Sub

Private Sub DataGridView1_RowPrePaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
   'フォーカス枠を描画しない
    e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    DataGridView1.DataSource = <DB>
   'デフォルトの行選択をしない
    DataGridView1.CurrentCell = Nothing
    Dim i As Integer
    For i = 0 To DataGridView1.Rows.Count - 1
       'セルの値に応じて行を色分け
        DataGridView1.Rows(i).DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromOle(Integer.Parse(DataGridView1.Item(0, i).Value.ToString()))
        DataGridView1.Rows(i).DefaultCellStyle.BackColor = System.Drawing.ColorTranslator.FromOle(Integer.Parse(DataGridView1.Item(1, i).Value.ToString()))
       '選択した時の色を、行の背景色と同じにする
        DataGridView1.Rows(i).DefaultCellStyle.SelectionForeColor = DataGridView1.Rows(i).DefaultCellStyle.ForeColor
        DataGridView1.Rows(i).DefaultCellStyle.SelectionBackColor = DataGridView1.Rows(i).DefaultCellStyle.BackColor
    Next
End Sub