How to DataGridView Template


There are situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView cell style properties. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. When displaying external data, however, the rows are generated automatically, but they are based on the row template, which you can set to an instance of your custom row type.

The following code example illustrates how to use the row template to specify an initial row height and a minimum row height and BackColor.

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim row As DataGridViewRow = Me.DataGridView1.RowTemplate
        row.DefaultCellStyle.BackColor = Color.Bisque
        row.Height = 35
        row.MinimumHeight = 20

        Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
        Dim sql As String = "SELECT * FROM Authors"
        Dim connection As New SqlConnection(connectionString)
        Dim dataadapter As New SqlDataAdapter(sql, connection)
        Dim ds As New DataSet()
        dataadapter.Fill(ds, "Authors_table")
        DataGridView1.DataSource = ds
        DataGridView1.DataMember = "Authors_table"

    End Sub
End Class