How to Formatting in DataGridView

datagrid-formating

The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications.

The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. Typically, however, multiple cells will share particular style characteristics. You can define appearance and formatting styles for individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the DataGridViewCellStyle objects accessed through various DataGridView control properties.

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






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