Partial Public Class Form1 Private tbl As DataTable Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load '今回はコードで DataTable の定義を記述していますが、型付きDataSet を使うのもお奨めです。 tbl = New DataTable() tbl.Columns.Add("時刻", GetType(Date)) tbl.Columns.Add("背景色", GetType(Color)) 'データバインド関連の情報。コードではなく、デザイン時に指定しておいても OK。 Dim col As New DataGridViewTextBoxColumn() col.HeaderText = "Time" col.DataPropertyName = "時刻" col.DefaultCellStyle.Format = "HH:mm:ss.ffff" col.ReadOnly = True DataGridView1.Columns.Add(col) DataGridView1.AutoGenerateColumns = False 'True の場合は、背景色の列も追加される DataGridView1.AllowUserToAddRows = False DataGridView1.DataSource = tbl '★DataTable をセット DataGridView1.DefaultCellStyle.SelectionBackColor = SystemColors.Window DataGridView1.DefaultCellStyle.SelectionForeColor = SystemColors.WindowText End Sub Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _ ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting If e.RowIndex >= 0 Then 'RowIndex = -1 は列ヘッダーの行を指す 'DataGridView1.InvalidateRow(e.RowIndex) 'これは、行全体を再描画する場合に利用 'バインド元の行を取り出す場合は、DataBoundItem プロパティを利用する Dim rowView As DataRowView = TryCast(DataGridView1.Rows(e.RowIndex).DataBoundItem, DataRowView) If rowView IsNot Nothing Then Dim row As DataRow = rowView.Row e.CellStyle.BackColor = DirectCast(row("背景色"), Color) End If End If End Sub '先頭にピンクの行を追加 Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click Dim newRow As DataRow = tbl.NewRow() newRow("時刻") = Now newRow("背景色") = Color.Pink tbl.Rows.InsertAt(newRow, 0) End Sub '末尾に水色の行を追加 Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click Dim newRow As DataRow = tbl.NewRow() newRow("時刻") = Now newRow("背景色") = Color.LightCyan tbl.Rows.Add(newRow) End Sub '先頭にランダムな色を追加 Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click Dim r As New Random() Dim newRow As DataRow = tbl.NewRow() newRow("時刻") = Now newRow("背景色") = Color.FromArgb(255, r.Next(256), r.Next(256), r.Next(256)) tbl.Rows.InsertAt(newRow, 0) End Sub End Class