'案2:隣接行の拝啓 Public Class Form1 Private WithEvents dgv As DataGridView Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load dgv = New DataGridView() dgv.AllowUserToAddRows = False 'dgv.EditMode = DataGridViewEditMode.EditOnEnter dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect dgv.ColumnCount = 5 dgv.RowCount = 100 dgv.Dock = DockStyle.Fill Controls.Add(dgv) End Sub Private Sub dgv_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles dgv.CellFormatting If e.RowIndex < 0 OrElse e.ColumnIndex < 0 Then Return End If Dim pos As Point = dgv.CurrentCellAddress Dim recordRows As New List(Of Integer)() From {pos.Y, pos.Y + If(pos.Y Mod 2 = 0, 1, -1)} If recordRows.Contains(e.RowIndex) Then e.CellStyle.BackColor = If((e.RowIndex \ 2) Mod 2 = 0, Color.LightGreen, Color.Khaki) Else e.CellStyle.BackColor = If((e.RowIndex \ 2) Mod 2 = 0, Color.GreenYellow, Color.Yellow) End If e.CellStyle.SelectionBackColor = e.CellStyle.BackColor End Sub Private Sub dgv_RowEnter(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgv.RowEnter dgv.Invalidate() End Sub End Class
'案3 Public Class Form1 Private WithEvents dgv As DataGridView Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load dgv = New DataGridView() dgv.AllowUserToAddRows = False 'dgv.EditMode = DataGridViewEditMode.EditOnEnter dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect dgv.ColumnCount = 5 dgv.RowCount = 100 dgv.MultiSelect = True dgv.Dock = DockStyle.Fill dgv.DefaultCellStyle.BackColor = Color.Yellow dgv.DefaultCellStyle.SelectionBackColor = Color.Khaki Controls.Add(dgv) End Sub Private Sub dgv_CellFormatting(ByVal sender As Object, _ ByVal e As DataGridViewCellFormattingEventArgs) Handles dgv.CellFormatting If e.RowIndex >= 0 AndAlso (e.RowIndex \ 2) Mod 2 = 0 Then e.CellStyle.BackColor = Color.GreenYellow e.CellStyle.SelectionBackColor = Color.LightGreen End If End Sub Private Sub dgv_RowEnter(ByVal sender As Object, _ ByVal e As DataGridViewCellEventArgs) Handles dgv.RowEnter Dim pairRow As Integer = e.RowIndex + If(e.RowIndex Mod 2 = 0, 1, -1) dgv.ClearSelection() dgv.Rows(e.RowIndex).Selected = True dgv.Rows(pairRow).Selected = True End Sub End Class