Export (0) Print
Expand All

DataGridViewColumn Class

Represents a column in a DataGridView control.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

Public Class DataGridViewColumn _
	Inherits DataGridViewBand _
	Implements IComponent, IDisposable

The DataGridViewColumn type exposes the following members.

Public methodDataGridViewColumnInitializes a new instance of the DataGridViewColumn class to the default state.
Public methodDataGridViewColumn(DataGridViewCell)Initializes a new instance of the DataGridViewColumn class using an existing DataGridViewCell as a template.

Public propertyAutoSizeModeGets or sets the mode by which the column automatically adjusts its width.
Public propertyCellTemplateGets or sets the template used to create new cells.
Public propertyCellTypeGets the run-time type of the cell template.
Public propertyContextMenuStripGets or sets the shortcut menu for the column. (Overrides DataGridViewBand.ContextMenuStrip.)
Public propertyDataGridViewGets the DataGridView control associated with this element. (Inherited from DataGridViewElement.)
Public propertyDataPropertyNameGets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.
Public propertyDefaultCellStyleGets or sets the column's default cell style. (Overrides DataGridViewBand.DefaultCellStyle.)
Public propertyDefaultHeaderCellTypeGets or sets the run-time type of the default header cell. (Inherited from DataGridViewBand.)
Public propertyDisplayedGets a value indicating whether the band is currently displayed onscreen. (Inherited from DataGridViewBand.)
Public propertyDisplayIndexGets or sets the display order of the column relative to the currently displayed columns.
Public propertyDividerWidthGets or sets the width, in pixels, of the column divider.
Public propertyFillWeightGets or sets a value that represents the width of the column when it is in fill mode relative to the widths of other fill-mode columns in the control.
Public propertyFrozenGets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally. (Overrides DataGridViewBand.Frozen.)
Public propertyHasDefaultCellStyleGets a value indicating whether the DefaultCellStyle property has been set. (Inherited from DataGridViewBand.)
Public propertyHeaderCellGets or sets the DataGridViewColumnHeaderCell that represents the column header.
Protected propertyHeaderCellCoreGets or sets the header cell of the DataGridViewBand. (Inherited from DataGridViewBand.)
Public propertyHeaderTextGets or sets the caption text on the column's header cell.
Public propertyIndexGets the relative position of the band within the DataGridView control. (Inherited from DataGridViewBand.)
Public propertyInheritedAutoSizeModeGets the sizing mode in effect for the column.
Public propertyInheritedStyleGets the cell style currently applied to the column. (Overrides DataGridViewBand.InheritedStyle.)
Public propertyIsDataBoundGets a value indicating whether the column is bound to a data source.
Protected propertyIsRowGets a value indicating whether the band represents a row. (Inherited from DataGridViewBand.)
Public propertyMinimumWidthGets or sets the minimum width, in pixels, of the column.
Public propertyNameGets or sets the name of the column.
Public propertyReadOnlyGets or sets a value indicating whether the user can edit the column's cells. (Overrides DataGridViewBand.ReadOnly.)
Public propertyResizableGets or sets a value indicating whether the column is resizable. (Overrides DataGridViewBand.Resizable.)
Public propertySelectedGets or sets a value indicating whether the band is in a selected user interface (UI) state. (Inherited from DataGridViewBand.)
Public propertySiteInfrastructure. Gets or sets the site of the column.
Public propertySortModeGets or sets the sort mode for the column.
Public propertyStateGets the user interface (UI) state of the element. (Inherited from DataGridViewElement.)
Public propertyTagGets or sets the object that contains data to associate with the band. (Inherited from DataGridViewBand.)
Public propertyToolTipTextGets or sets the text used for ToolTips.
Public propertyValueTypeGets or sets the data type of the values in the column's cells.
Public propertyVisibleGets or sets a value indicating whether the column is visible. (Overrides DataGridViewBand.Visible.)
Public propertyWidthGets or sets the current width of the column.

Public methodCloneCreates an exact copy of this band. (Overrides DataGridViewBand.Clone.)
Public methodDisposeReleases all resources used by the DataGridViewBand. (Inherited from DataGridViewBand.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources. (Overrides DataGridViewBand.Dispose(Boolean).)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases the resources associated with the band. (Inherited from DataGridViewBand.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetPreferredWidthCalculates the ideal width of the column based on the specified criteria.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnDataGridViewChangedCalled when the band is associated with a different DataGridView. (Inherited from DataGridViewBand.)
Protected methodRaiseCellClickRaises the DataGridView.CellClick event. (Inherited from DataGridViewElement.)
Protected methodRaiseCellContentClickRaises the DataGridView.CellContentClick event. (Inherited from DataGridViewElement.)
Protected methodRaiseCellContentDoubleClickRaises the DataGridView.CellContentDoubleClick event. (Inherited from DataGridViewElement.)
Protected methodRaiseCellValueChangedRaises the DataGridView.CellValueChanged event. (Inherited from DataGridViewElement.)
Protected methodRaiseDataErrorRaises the DataGridView.DataError event. (Inherited from DataGridViewElement.)
Protected methodRaiseMouseWheelRaises the Control.MouseWheel event. (Inherited from DataGridViewElement.)
Public methodToStringGets a string that describes the column. (Overrides DataGridViewBand.ToString.)

Public eventDisposedOccurs when the DataGridViewColumn is disposed.

The DataGridViewColumn class represents a logical column in a DataGridView control. You can retrieve columns through the Columns collection of the control.

Unlike a DataGridViewRow, which contains the actual collection of cells in a DataGridView, DataGridViewColumn is used mainly to adjust the appearance and behavior of the column user interface (UI), such as column width and cell style. For more information about cell styles, see Cell Styles in the Windows Forms DataGridView Control.

Types that derive from DataGridViewColumn typically initialize the CellTemplate property to a new instance of a related type derived from the DataGridViewCell class. Any column properties that relate to the appearance or behavior of individual cells are wrappers for the corresponding properties of the template cell. Changing one of these properties on the column automatically changes the value on the cell template and on all cells in the column. To override the specified value for individual cells, set the cell values after you set the column value.

Notes to Inheritors

When you derive from DataGridViewColumn and add new properties to the derived class, be sure to override the Clone method to copy the new properties during cloning operations. You should also call the base class's Clone method so that the properties of the base class are copied to the new cell.

The following code example creates a Windows Form with a DataGridView and a set of buttons. Each button label describes an operation related to a DataGridViewColumn property, such as swapping the first and last column (using the DisplayIndex property) or changing the text of a column header (using the HeaderText property). Clicking a button changes the associated property of the DataGridViewColumn.

Imports System.Windows.Forms
Imports System.Drawing

Public Class DataGridViewColumnDemo
    Inherits Form

#Region "set up form" 
    Public Sub New()

        AddButton(Button1, "Reset")
        AddButton(Button2, "Change Column 3 Header")
        AddButton(Button3, "Change Meatloaf Recipe")
    End Sub 

    Friend WithEvents dataGridView As DataGridView
    Friend WithEvents Button1 As Button = New Button()
    Friend WithEvents Button2 As Button = New Button()
    Friend WithEvents Button3 As Button = New Button()
    Friend WithEvents Button4 As Button = New Button()
    Friend WithEvents Button5 As Button = New Button()
    Friend WithEvents Button6 As Button = New Button()
    Friend WithEvents Button7 As Button = New Button()
    Friend WithEvents Button8 As Button = New Button()
    Friend WithEvents Button9 As Button = New Button()
    Friend WithEvents Button10 As Button = New Button()
    Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel _
        = New FlowLayoutPanel()

    Private Sub InitializeComponent()
        FlowLayoutPanel1.Location = New Point(454, 0)
        FlowLayoutPanel1.AutoSize = True
        FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown
        FlowLayoutPanel1.Name = "flowlayoutpanel"
        ClientSize = New System.Drawing.Size(614, 360)
        Text = Me.GetType.Name
        AutoSize = True 
    End Sub
#End Region

#Region "set up DataGridView" 
    Private thirdColumnHeader As String = "Main Ingredients" 
    Private boringMeatloaf As String = "ground beef" 
    Private boringMeatloafRanking As String = "*" 
    Private boringRecipe As Boolean 
    Private shortMode As Boolean 

    Private Sub InitializeDataGridView(ByVal ignored As Object, _
    ByVal ignoredToo As EventArgs) Handles Me.Load

        dataGridView = New System.Windows.Forms.DataGridView
        dataGridView.Size = New Size(300, 200)

        ' Create an unbound DataGridView by declaring a 
        ' column count.
        dataGridView.ColumnCount = 4

        ' Set the column header style. 
        Dim columnHeaderStyle As New DataGridViewCellStyle
        columnHeaderStyle.BackColor = Color.Aqua
        columnHeaderStyle.Font = _
            New Font("Verdana", 10, FontStyle.Bold)
        dataGridView.ColumnHeadersDefaultCellStyle = _

        ' Set the column header names.
        dataGridView.Columns(0).Name = "Recipe"
        dataGridView.Columns(1).Name = "Category"
        dataGridView.Columns(2).Name = thirdColumnHeader
        dataGridView.Columns(3).Name = "Rating"


        ' Populate the rows. 
        Dim row1 As String() = New String() _
            {"Meatloaf", "Main Dish", boringMeatloaf, _
        Dim row2 As String() = New String() _
            {"Key Lime Pie", "Dessert", _
            "lime juice, evaporated milk", _
        Dim row3 As String() = New String() _
            {"Orange-Salsa Pork Chops", "Main Dish", _
            "pork chops, salsa, orange juice", "****"}
        Dim row4 As String() = New String() _
            {"Black Bean and Rice Salad", "Salad", _
            "black beans, brown rice", _
        Dim row5 As String() = New String() _
            {"Chocolate Cheesecake", "Dessert", "cream cheese", _
        Dim row6 As String() = New String() _
            {"Black Bean Dip", "Appetizer", _
            "black beans, sour cream", _
        Dim rows As Object() = New Object() {row1, row2, _
            row3, row4, row5, row6}

        Dim rowArray As String()
        For Each rowArray In rows

        shortMode = False
        boringRecipe = True 
    End Sub 

    Private Sub AddButton(ByVal button As Button, _
        ByVal buttonLabel As String)

        button.TabIndex = FlowLayoutPanel1.Controls.Count
        button.Text = buttonLabel
        button.AutoSize = True 
    End Sub 

    Private Sub ResetToDisorder(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click
        InitializeDataGridView(Nothing, Nothing)
    End Sub 

    Private Sub ChangeColumn3Header(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button2.Click

        If shortMode Then dataGridView.Columns(2).HeaderText = _
            "S" _
            Else dataGridView.Columns(2).HeaderText = _
    End Sub 

    Private Shared Sub Toggle(ByRef toggleThis As Boolean)
        toggleThis = Not toggleThis
    End Sub 

    Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button3.Click

        If boringRecipe Then
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
            Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
                & "1/2 cup bread crumbs, 1/4 cup ketchup," _
                & "1/3 tsp onion powder, " _
                & "1 clove of garlic, 1/2 pack onion soup mix " _
                & " dash of your favorite BBQ Sauce"
            SetMeatloaf(greatMeatloafRecipe, "***")
        End If 
    End Sub 

    Private Sub SetMeatloaf(ByVal recipe As String, _
        ByVal rating As String)

        dataGridView.Rows(0).Cells(2).Value = recipe
        dataGridView.Rows(0).Cells(3).Value = rating
    End Sub
#End Region

#Region "demonstration code" 
    Private Sub PostColumnCreation()
    End Sub 

    Private criteriaLabel As String = "Column 3 sizing criteria: " 
    Private Sub AddCriteriaLabel()
        AddLabelToPanelIfNotAlreadyThere(criteriaLabel, _
            criteriaLabel & _
            dataGridView.Columns(2).AutoSizeMode.ToString() _
            & ".")
    End Sub 

    Private Sub AddContextLabel()
        Dim labelName As String = "label"
        AddLabelToPanelIfNotAlreadyThere(labelName, _
            "Use shortcut menu to change cell color.")
    End Sub 

    Private Sub AddLabelToPanelIfNotAlreadyThere( _
    ByVal labelName As String, _
    ByVal labelText As String)

        Dim label As Label
        If FlowLayoutPanel1.Controls(labelName) Is Nothing Then
            label = New Label()
            label.AutoSize = True
            label.Name = labelName
            label.BackColor = Color.Bisque
            label = CType(FlowLayoutPanel1.Controls(labelName), Label)
        End If
        label.Text = labelText
    End Sub 

    Private Sub CustomizeCellsInThirdColumn()

        Dim thirdColumn As Integer = 2
        Dim column As DataGridViewColumn = _
        Dim cell As DataGridViewCell = _
            New DataGridViewTextBoxCell()

        cell.Style.BackColor = Color.Wheat
        column.CellTemplate = cell
    End Sub 

    WithEvents toolStripItem1 As New ToolStripMenuItem()

    Private Sub AddContextMenu()
        toolStripItem1.Text = "Redden" 
        Dim strip As New ContextMenuStrip()
        For Each column As DataGridViewColumn _
            In dataGridView.Columns()

            column.ContextMenuStrip = strip
    End Sub 
    ' Change the cell's color. 
    Private Sub toolStripItem1_Click(ByVal sender As Object, _
        ByVal args As EventArgs) _
        Handles toolStripItem1.Click

        dataGridView.Rows(mouseLocation.RowIndex) _
            .Cells(mouseLocation.ColumnIndex) _
            .Style.BackColor = Color.Red
    End Sub 

    Private mouseLocation As DataGridViewCellEventArgs

    ' Deal with hovering over a cell. 
    Private Sub dataGridView_CellMouseEnter(ByVal sender As Object, _
        ByVal location As DataGridViewCellEventArgs) _
        Handles DataGridView.CellMouseEnter

        mouseLocation = location
    End Sub 

    Private Sub SetDefaultCellInFirstColumn()
        Dim firstColumn As DataGridViewColumn = _
        Dim cellStyle As DataGridViewCellStyle = _
            New DataGridViewCellStyle()
        cellStyle.BackColor = Color.Thistle

        firstColumn.DefaultCellStyle = cellStyle
    End Sub 

    Private Sub ToolTips()
        Dim firstColumn As DataGridViewColumn = _
        Dim thirdColumn As DataGridViewColumn = _
        firstColumn.ToolTipText = _
            "This is column uses a default cell."
        thirdColumn.ToolTipText = _
            "This is column uses a template cell." _
            & " Changes to one cell's style changes them all." 
    End Sub 

    Private Sub AddAdditionalButtons()
        AddButton(Button4, "Set Minimum Width of Column Two")
        AddButton(Button5, "Set Width of Column One")
        AddButton(Button6, "Autosize Third Column")
        AddButton(Button7, "Add Thick Vertical Edge")
        AddButton(Button8, "Style and Number Columns")
        AddButton(Button9, "Change Column Header Text")
        AddButton(Button10, "Swap First and Last Columns")
    End Sub 

    Private Sub AdjustDataGridViewSizing()
        dataGridView.ColumnHeadersHeightSizeMode = _
    End Sub 

    'Set the minimum width. 
    Private Sub Button4_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button4.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(1)
        column.MinimumWidth = 40
    End Sub 

    ' Set the width. 
    Private Sub Button5_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button5.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(0)
        column.Width = 60
    End Sub 

    ' AutoSize the third column. 
    Private Sub Button6_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button6.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(2)
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
    End Sub 

    ' Set the vertical edge. 
    Private Sub Button7_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button7.Click

        Dim thirdColumn As Integer = 2
        Dim column As DataGridViewColumn = _
        column.DividerWidth = 10

    End Sub 

    ' Style and number columns. 
    Private Sub Button8_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button8.Click

        Dim style As DataGridViewCellStyle = _
            New DataGridViewCellStyle()
        style.Alignment = _
        style.ForeColor = Color.IndianRed
        style.BackColor = Color.Ivory

        For Each column As DataGridViewColumn _
            In dataGridView.Columns

            column.HeaderCell.Value = _
            column.HeaderCell.Style = style
    End Sub 

    ' Change the text in the column header. 
    Private Sub Button9_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button9.Click

        For Each column As DataGridViewColumn _
            In dataGridView.Columns

            column.HeaderText = String.Concat("Column ", _
    End Sub 

    ' Swap the last column with the first. 
    Private Sub Button10_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button10.Click

        Dim columnCollection As DataGridViewColumnCollection = _

        Dim firstVisibleColumn As DataGridViewColumn = _
        Dim lastVisibleColumn As DataGridViewColumn = _
            columnCollection.GetLastColumn(DataGridViewElementStates.Visible, _

        Dim firstColumn_sIndex As Integer = firstVisibleColumn.DisplayIndex
        firstVisibleColumn.DisplayIndex = _
        lastVisibleColumn.DisplayIndex = firstColumn_sIndex
    End Sub 

    ' Updated the criteria label. 
    Private Sub dataGridView_AutoSizeColumnCriteriaChanged( _
        ByVal sender As Object, _
        ByVal args As DataGridViewAutoSizeColumnModeEventArgs) _
        Handles DataGridView.AutoSizeColumnModeChanged

        args.Column.DataGridView.Parent. _
        Controls("flowlayoutpanel"). _
        Controls(criteriaLabel).Text = _
            criteriaLabel & args.Column.AutoSizeMode.ToString
    End Sub
#End Region

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

End Class

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

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