How to Formatting in DataGridView

The DataGridView control offers a high level of configurability and extensibility, providing developers with numerous properties, methods, and events to customize its appearance and behavior according to their specific application requirements.

While the DataGridView control allows for defining the basic appearance and formatting of individual cells and their values, it is common for multiple cells to share similar style characteristics. In such cases, it is more efficient to define appearance and formatting styles that can be applied to multiple cells.

DataGridViewCellStyle objects


To achieve this, you can set the properties of DataGridViewCellStyle objects, which represent the styles for cells, accessed through various properties of the DataGridView control. These properties enable you to define appearance and formatting styles for individual cells, cells in specific columns and rows, or even for all cells within the control.

The following program shows how to implement different ways of cell formatting in a DataGridView control.

Full Source VB.NET
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 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() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" DataGridView1.GridColor = Color.Red DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None DataGridView1.BackgroundColor = Color.LightGray DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True] DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect DataGridView1.AllowUserToResizeColumns = False DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End Sub End Class