55 out of 74 rated this helpful - Rate this topic

DataGridView Class

Displays data in a customizable grid.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
'Declaration
<ComplexBindingPropertiesAttribute("DataSource", "DataMember")> _
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
<DockingAttribute(DockingBehavior.Ask)> _
Public Class DataGridView _
	Inherits Control _
	Implements ISupportInitialize
'Usage
Dim instance As DataGridView

The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor. For more information, see Basic Formatting and Styling in the Windows Forms DataGridView Control.

You can use a DataGridView control to display data with or without an underlying data source. Without specifying a data source, you can create columns and rows that contain data and add them directly to the DataGridView using the Rows and Columns properties. You can also use the Rows collection to access DataGridViewRow objects and the DataGridViewRow.Cells property to read or write cell values directly. The Item indexer also provides direct access to cells.

As an alternative to populating the control manually, you can set the DataSource and DataMember properties to bind the DataGridView to a data source and automatically populate it with data. For more information, see Displaying Data in the Windows Forms DataGridView Control.

When working with very large amounts of data, you can set the VirtualMode property to true to display a subset of the available data. Virtual mode requires the implementation of a data cache from which the DataGridView control is populated. For more information, see Data Display Modes in the Windows Forms DataGridView Control.

For additional information about the features available in the DataGridView control, see DataGridView Control (Windows Forms). The following table provides direct links to common tasks.

TopicLocation
How to: Change the Type of a Windows Forms DataGridView Column Using the Designer
How to: Bind Data to the Windows Forms DataGridView Control Using the Designer
How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer
How to: Change the Type of a Windows Forms DataGridView Column Using the DesignerWindows Forms Controls
How to: Bind Data to the Windows Forms DataGridView Control Using the DesignerWindows Forms Controls
How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the DesignerWindows Forms Controls
How to: Bind Data to the Windows Forms DataGridView Control
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control
How to: Set Font and Color Styles in the Windows Forms DataGridView Control
How to: Format Data in the Windows Forms DataGridView Control
Walkthrough: Validating Data in the Windows Forms DataGridView Control
How to: Customize Data Formatting in the Windows Forms DataGridView Control
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls
How to: Bind Data to the Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
How to: Set Font and Color Styles in the Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
How to: Format Data in the Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
Walkthrough: Validating Data in the Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
How to: Customize Data Formatting in the Windows Forms DataGridView ControlWindows Forms Controls in the .NET Framework SDK
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ControlsWindows Forms Controls in the .NET Framework SDK
How to: Bind Data to the Windows Forms DataGridView Control
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control
How to: Set Font and Color Styles in the Windows Forms DataGridView Control
How to: Change the Type of a Windows Forms DataGridView Column Using the Designer
How to: Bind Data to the Windows Forms DataGridView Control Using the Designer
How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer
How to: Format Data in the Windows Forms DataGridView Control
Walkthrough: Validating Data in the Windows Forms DataGridView Control
How to: Customize Data Formatting in the Windows Forms DataGridView Control
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls

Although the DataGridView control replaces and adds functionality to the DataGrid control of previous versions, the DataGrid control is retained for both backward compatibility and future use if you choose. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.

NoteNote:

The DataGridView control inherits both the ContextMenu and ContextMenuStrip properties from Control, but supports only the ContextMenuStrip property. Using the ContextMenu property with the DataGridView control has no effect.

The following code example demonstrates how to initialize an unbound DataGridView control.

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private buttonPanel As New Panel
    Private WithEvents songsDataGridView As New DataGridView
    Private WithEvents addNewRowButton As New Button
    Private WithEvents deleteRowButton As New Button

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        SetupLayout()
        SetupDataGridView()
        PopulateDataGridView()

    End Sub 

    Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
        Handles songsDataGridView.CellFormatting

        If e IsNot Nothing Then 

            If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
            "Release Date" Then 
                If e.Value IsNot Nothing Then 
                    Try
                        e.Value = DateTime.Parse(e.Value.ToString()) _
                            .ToLongDateString()
                        e.FormattingApplied = True 
                    Catch ex As FormatException
                        Console.WriteLine("{0} is not a valid date.", e.Value.ToString())
                    End Try 
                End If 
            End If 

        End If 

    End Sub 

    Private Sub addNewRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles addNewRowButton.Click

        Me.songsDataGridView.Rows.Add()

    End Sub 

    Private Sub deleteRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles deleteRowButton.Click

        If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _
            Not Me.songsDataGridView.SelectedRows(0).Index = _
            Me.songsDataGridView.Rows.Count - 1 Then 

            Me.songsDataGridView.Rows.RemoveAt( _
                Me.songsDataGridView.SelectedRows(0).Index)

        End If 

    End Sub 

    Private Sub SetupLayout()

        Me.Size = New Size(600, 500)

        With addNewRowButton
            .Text = "Add Row"
            .Location = New Point(10, 10)
        End With 

        With deleteRowButton
            .Text = "Delete Row"
            .Location = New Point(100, 10)
        End With 

        With buttonPanel
            .Controls.Add(addNewRowButton)
            .Controls.Add(deleteRowButton)
            .Height = 50
            .Dock = DockStyle.Bottom
        End With 

        Me.Controls.Add(Me.buttonPanel)

    End Sub 

    Private Sub SetupDataGridView()

        Me.Controls.Add(songsDataGridView)

        songsDataGridView.ColumnCount = 5
        With songsDataGridView.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(songsDataGridView.Font, FontStyle.Bold)
        End With 

        With songsDataGridView
            .Name = "songsDataGridView"
            .Location = New Point(8, 8)
            .Size = New Size(500, 250)
            .AutoSizeRowsMode = _
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
            .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
            .CellBorderStyle = DataGridViewCellBorderStyle.Single
            .GridColor = Color.Black
            .RowHeadersVisible = False

            .Columns(0).Name = "Release Date"
            .Columns(1).Name = "Track"
            .Columns(2).Name = "Title"
            .Columns(3).Name = "Artist"
            .Columns(4).Name = "Album"
            .Columns(4).DefaultCellStyle.Font = _
                New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic)

            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False
            .Dock = DockStyle.Fill
        End With 

    End Sub 

    Private Sub PopulateDataGridView()

        Dim row0 As String() = {"11/22/1968", "29", "Revolution 9", _
            "Beatles", "The Beatles [White Album]"}
        Dim row1 As String() = {"1960", "6", "Fools Rush In", _
            "Frank Sinatra", "Nice 'N' Easy"}
        Dim row2 As String() = {"11/11/1971", "1", "One of These Days", _
            "Pink Floyd", "Meddle"}
        Dim row3 As String() = {"1988", "7", "Where Is My Mind?", _
            "Pixies", "Surfer Rosa"}
        Dim row4 As String() = {"5/1981", "9", "Can't Find My Mind", _
            "Cramps", "Psychedelic Jungle"}
        Dim row5 As String() = {"6/10/2003", "13", _
            "Scatterbrain. (As Dead As Leaves.)", _
            "Radiohead", "Hail to the Thief"}
        Dim row6 As String() = {"6/30/1992", "3", "Dress", "P J Harvey", "Dry"}

        With Me.songsDataGridView.Rows
            .Add(row0)
            .Add(row1)
            .Add(row2)
            .Add(row3)
            .Add(row4)
            .Add(row5)
            .Add(row6)
        End With 

        With Me.songsDataGridView
            .Columns(0).DisplayIndex = 3
            .Columns(1).DisplayIndex = 4
            .Columns(2).DisplayIndex = 0
            .Columns(3).DisplayIndex = 1
            .Columns(4).DisplayIndex = 2
        End With 

    End Sub


    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub 

End Class
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.