DataGridColumnStyle Class

Specifies the appearance, text formatting, and behavior of a System.Windows.Forms.DataGrid control column. This class is abstract.

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

'Declaration
Public MustInherit Class DataGridColumnStyle _
	Inherits Component _
	Implements IDataGridColumnStyleEditingNotificationService

The DataGridColumnStyle type exposes the following members.

  NameDescription
Public methodDataGridColumnStyleIn a derived class, initializes a new instance of the DataGridColumnStyle class.
Public methodDataGridColumnStyle(PropertyDescriptor)Initializes a new instance of the DataGridColumnStyle class with the specified PropertyDescriptor.
Top

  NameDescription
Public propertyAlignmentGets or sets the alignment of text in a column.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyDataGridTableStyleGets the DataGridTableStyle for the column.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Protected propertyFontHeightGets the height of the column's font.
Public propertyHeaderAccessibleObjectInfrastructure. Gets the AccessibleObject for the column.
Public propertyHeaderTextGets or sets the text of the column header.
Public propertyMappingNameGets or sets the name of the data member to map the column style to.
Public propertyNullTextGets or sets the text that is displayed when the column contains Nothing.
Public propertyPropertyDescriptorGets or sets the PropertyDescriptor that determines the attributes of data displayed by the DataGridColumnStyle.
Public propertyReadOnlyGets or sets a value indicating whether the data in the column can be edited.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Public propertyWidthGets or sets the width of the column.
Top

  NameDescription
Protected methodAbortWhen overridden in a derived class, initiates a request to interrupt an edit procedure.
Protected methodBeginUpdateSuspends the painting of the column until the EndUpdate method is called.
Protected methodCheckValidDataSourceThrows an exception if the System.Windows.Forms.DataGrid does not have a valid data source, or if this column is not mapped to a valid property in the data source.
Protected methodColumnStartedEditingInforms the System.Windows.Forms.DataGrid that the user has begun editing the column.
Protected methodCommitWhen overridden in a derived class, initiates a request to complete an editing procedure.
Protected methodConcedeFocusNotifies a column that it must relinquish the focus to the control it is hosting.
Protected methodCreateHeaderAccessibleObjectGets the AccessibleObject for the column.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDisposeReleases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Protected methodEdit(CurrencyManager, Int32, Rectangle, Boolean)Prepares a cell for editing.
Protected methodEdit(CurrencyManager, Int32, Rectangle, Boolean, String)Prepares the cell for editing using the specified CurrencyManager, row number, and Rectangle parameters.
Protected methodEdit(CurrencyManager, Int32, Rectangle, Boolean, String, Boolean)When overridden in a deriving class, prepares a cell for editing.
Protected methodEndUpdateResumes the painting of columns suspended by calling the BeginUpdate method.
Protected methodEnterNullValueEnters a DBNull.Value into the column.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Protected methodGetColumnValueAtRowGets the value in the specified row from the specified CurrencyManager.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetMinimumHeightWhen overridden in a derived class, gets the minimum height of a row.
Protected methodGetPreferredHeightWhen overridden in a derived class, gets the height used for automatically resizing columns.
Protected methodGetPreferredSizeWhen overridden in a derived class, gets the width and height of the specified value. The width and height are used when the user navigates to DataGridTableStyle using the DataGridColumnStyle.
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodInvalidateRedraws the column and causes a paint message to be sent to the control.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodPaint(Graphics, Rectangle, CurrencyManager, Int32)Paints the DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, and row number.
Protected methodPaint(Graphics, Rectangle, CurrencyManager, Int32, Boolean)When overridden in a derived class, paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, and alignment.
Protected methodPaint(Graphics, Rectangle, CurrencyManager, Int32, Brush, Brush, Boolean)Paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, background color, foreground color, and alignment.
Protected methodReleaseHostedControlAllows the column to free resources when the control it hosts is not needed.
Public methodResetHeaderTextResets the HeaderText to its default value, Nothing.
Protected methodSetColumnValueAtRowSets the value in a specified row with the value from a specified CurrencyManager.
Protected methodSetDataGridSets the System.Windows.Forms.DataGrid control that this column belongs to.
Protected methodSetDataGridInColumnSets the System.Windows.Forms.DataGrid for the column.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Protected methodUpdateUIUpdates the value of a specified row with the given text.
Top

  NameDescription
Public eventAlignmentChangedOccurs when the Alignment property value changes.
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventFontChangedOccurs when the column's font changes.
Public eventHeaderTextChangedOccurs when the HeaderText property value changes.
Public eventMappingNameChangedOccurs when the MappingName value changes.
Public eventNullTextChangedOccurs when the NullText value changes.
Public eventPropertyDescriptorChangedOccurs when the PropertyDescriptor property value changes.
Public eventReadOnlyChangedOccurs when the ReadOnly property value changes.
Public eventWidthChangedOccurs when the Width property value changes.
Top

  NameDescription
Explicit interface implemetationPrivate methodIDataGridColumnStyleEditingNotificationService.ColumnStartedEditingInforms the DataGrid control that the user has begun editing the column.
Top

The collection of DataGridColumnStyle objects (the GridColumnStylesCollection) is accessed through the System.Windows.Forms.DataGrid control's TableStyles property.

The System.Windows.Forms.DataGrid control automatically creates a collection of DataGridColumnStyle objects for you when you set the DataSource property to an appropriate data source. The objects created actually are instances of one of the following classes that inherit from DataGridColumnStyle: DataGridBoolColumn or DataGridTextBoxColumn class.

To format the data display, set the Format property of the DataGridTextBoxColumn class to one of the formatting values. For more information about valid formatting values, see Formatting Types and Custom Date and Time Format Strings.

You can also create your own set of DataGridColumnStyle objects and add them to the GridColumnStylesCollection. When you do so, you must set the MappingName of each column style to the ColumnName of a DataColumn to synchronize the display of columns with the actual data.

Caution noteCaution

Always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection before adding DataGridTableStyle objects to the GridTableStylesCollection. When you add an empty DataGridTableStyle with a valid MappingName value to the collection, DataGridColumnStyle objects are automatically generated for you. Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection.

When one of the derived classes is instantiated by a System.Windows.Forms.DataGrid control, the class created depends on the DataType of the DataColumn associated with the DataGridColumnStyle object. For example, a DataColumn with its DataType set to System.Boolean will be associated with a DataGridBoolColumn. To determine the type of any DataGridColumnStyle, use the GetType method.

To create your own column classes, you can inherit from DataGridColumnStyle. You might want to do this in order to create special columns that host controls, as exemplified by the DataGridTextBox class, which hosts the TextBox control. For example, you can host an Image control to show pictures in columns, or you can create your own user control to host in the column.

The functionality of the DataGridColumnStyle shouldn't be confused with that of the DataColumn. Whereas the DataColumn contains the properties and methods appropriate to creating a data table's schema, the DataGridColumnStyle contains the properties and methods related to the appearance of an individual column on the screen.

If a row contains a DBNull.Value, the text displayed in the column can be set with the NullText property.

The DataGridColumnStyle class also allows you to specify the behavior of a column while its data is being changed. The BeginUpdate and EndUpdate methods temporarily suspend the drawing of the column while large updates are being made to the column's data. Without this functionality, every change in every cell of the grid would be immediately drawn; this could be distracting to the user and a performance liability.

Several methods allow monitoring of the column as it is edited by the user, including the Edit and Commit events.

Most of the properties and methods of the class are tailored to controlling a column's appearance. But a few, such as the GetColumnValueAtRow and SetColumnValueAtRow allow you to examine and change the value in a specified cell.

Notes to Implementers

When you inherit from DataGridColumnStyle, you must override the following members: Abort, Commit, Edit, and Paint (twice).

The following code example creates a DataGridColumnStyle that hosts a DateTimePicker control.

Imports System
Imports System.Data
Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel
Imports System.Security.Permissions

' This example shows how to create your own column style that 
' hosts a control, in this case, a DateTimePicker. 
Public Class DataGridTimePickerColumn
    Inherits DataGridColumnStyle

    Private customDateTimePicker1 As New CustomDateTimePicker()

    ' The isEditing field tracks whether or not the user is 
    ' editing data with the hosted control. 
    Private isEditing As Boolean 

    Public Sub New()
        customDateTimePicker1.Visible = False 
    End Sub 

    Protected Overrides Sub Abort(ByVal rowNum As Integer)
        isEditing = False 
        RemoveHandler customDateTimePicker1.ValueChanged, _
            AddressOf TimePickerValueChanged
        Invalidate()
    End Sub 

    Protected Overrides Function Commit _
        (ByVal dataSource As CurrencyManager, ByVal rowNum As Integer) _
        As Boolean

        customDateTimePicker1.Bounds = Rectangle.Empty

        RemoveHandler customDateTimePicker1.ValueChanged, _
            AddressOf TimePickerValueChanged

        If Not isEditing Then 
            Return True 
        End If
        isEditing = False 

        Try 
            Dim value As DateTime = customDateTimePicker1.Value
            SetColumnValueAtRow(dataSource, rowNum, value)
        Catch 
        End Try

        Invalidate()
        Return True 
    End Function 

    Protected Overloads Overrides Sub Edit( _
        ByVal [source] As CurrencyManager, _
        ByVal rowNum As Integer, _
        ByVal bounds As Rectangle, _
        ByVal [readOnly] As Boolean, _
        ByVal displayText As String, _
        ByVal cellIsVisible As Boolean)

        Dim value As DateTime = _
        CType(GetColumnValueAtRow([source], rowNum), DateTime)
        If cellIsVisible Then
            customDateTimePicker1.Bounds = New Rectangle _
            (bounds.X + 2, bounds.Y + 2, bounds.Width - 4, _
            bounds.Height - 4)

            customDateTimePicker1.Value = value
            customDateTimePicker1.Visible = True 
            AddHandler customDateTimePicker1.ValueChanged, _
            AddressOf TimePickerValueChanged
        Else
            customDateTimePicker1.Value = value
            customDateTimePicker1.Visible = False 
        End If 

        If customDateTimePicker1.Visible Then
            DataGridTableStyle.DataGrid.Invalidate(bounds)
        End If

        customDateTimePicker1.Focus()

    End Sub 

    Protected Overrides Function GetPreferredSize( _
        ByVal g As Graphics, _
        ByVal value As Object) As Size

        Return New Size(100, customDateTimePicker1.PreferredHeight + 4)

    End Function 

    Protected Overrides Function GetMinimumHeight() As Integer 
        Return customDateTimePicker1.PreferredHeight + 4
    End Function 

    Protected Overrides Function GetPreferredHeight( _
        ByVal g As Graphics, ByVal value As Object) As Integer 

        Return customDateTimePicker1.PreferredHeight + 4

    End Function 

    Protected Overloads Overrides Sub Paint( _
        ByVal g As Graphics, ByVal bounds As Rectangle, _
        ByVal [source] As CurrencyManager, ByVal rowNum As Integer)

        Paint(g, bounds, [source], rowNum, False)

    End Sub 

    Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
        ByVal bounds As Rectangle, ByVal [source] As CurrencyManager, _
        ByVal rowNum As Integer, ByVal alignToRight As Boolean)

        Paint(g, bounds, [source], rowNum, Brushes.Red, _
            Brushes.Blue, alignToRight)

    End Sub 

    Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
        ByVal bounds As Rectangle, ByVal [source] As CurrencyManager, _
        ByVal rowNum As Integer, ByVal backBrush As Brush, _
        ByVal foreBrush As Brush, ByVal alignToRight As Boolean)

        Dim [date] As DateTime = _
        CType(GetColumnValueAtRow([source], rowNum), DateTime)
        Dim rect As Rectangle = bounds
        g.FillRectangle(backBrush, rect)
        rect.Offset(0, 2)
        rect.Height -= 2
        g.DrawString([date].ToString("d"), _
            Me.DataGridTableStyle.DataGrid.Font, foreBrush, _
            RectangleF.FromLTRB(rect.X, rect.Y, rect.Right, rect.Bottom))

    End Sub 

    Protected Overrides Sub SetDataGridInColumn(ByVal value As DataGrid)
        MyBase.SetDataGridInColumn(value)
        If (customDateTimePicker1.Parent IsNot Nothing) Then
            customDateTimePicker1.Parent.Controls.Remove(customDateTimePicker1)
        End If 
        If (value IsNot Nothing) Then
            value.Controls.Add(customDateTimePicker1)
        End If 
    End Sub 

    Private Sub TimePickerValueChanged( _
        ByVal sender As Object, ByVal e As EventArgs)

        ' Remove the handler to prevent it from being called twice in a row. 
        RemoveHandler customDateTimePicker1.ValueChanged, _
            AddressOf TimePickerValueChanged
        Me.isEditing = True 
        MyBase.ColumnStartedEditing(customDateTimePicker1)

    End Sub 

End Class 

Public Class CustomDateTimePicker
    Inherits DateTimePicker

    <SecurityPermissionAttribute( _
    SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _
    Protected Overrides Function ProcessKeyMessage(ByRef m As Message) As Boolean 
        ' Keep all the keys for the DateTimePicker. 
        Return ProcessKeyEventArgs(m)
    End Function 

End Class 

Public Class MyForm
    Inherits Form

    Private namesDataTable As DataTable
    Private myGrid As DataGrid = New DataGrid()

    Public Sub New()

        InitForm()

        namesDataTable = New DataTable("NamesTable")
        namesDataTable.Columns.Add(New DataColumn("Name"))
        Dim dateColumn As DataColumn = _
             New DataColumn("Date", GetType(DateTime))
        dateColumn.DefaultValue = DateTime.Today
        namesDataTable.Columns.Add(dateColumn)
        Dim namesDataSet As DataSet = New DataSet()
        namesDataSet.Tables.Add(namesDataTable)
        myGrid.DataSource = namesDataSet
        myGrid.DataMember = "NamesTable"
        AddGridStyle()
        AddData()

    End Sub 

    Private Sub AddGridStyle()
        Dim myGridStyle As DataGridTableStyle = _
                    New DataGridTableStyle()
        myGridStyle.MappingName = "NamesTable" 

        Dim nameColumnStyle As DataGridTextBoxColumn = _
            New DataGridTextBoxColumn()
        nameColumnStyle.MappingName = "Name"
        nameColumnStyle.HeaderText = "Name"
        myGridStyle.GridColumnStyles.Add(nameColumnStyle)

        Dim customDateTimePicker1ColumnStyle As DataGridTimePickerColumn = _
            New DataGridTimePickerColumn()
        customDateTimePicker1ColumnStyle.MappingName = "Date"
        customDateTimePicker1ColumnStyle.HeaderText = "Date"
        customDateTimePicker1ColumnStyle.Width = 100
        myGridStyle.GridColumnStyles.Add(customDateTimePicker1ColumnStyle)

        myGrid.TableStyles.Add(myGridStyle)
    End Sub 

    Private Sub AddData()
        Dim dRow As DataRow = namesDataTable.NewRow()
        dRow("Name") = "Name 1"
        dRow("Date") = New DateTime(2001, 12, 1)
        namesDataTable.Rows.Add(dRow)

        dRow = namesDataTable.NewRow()
        dRow("Name") = "Name 2"
        dRow("Date") = New DateTime(2001, 12, 4)
        namesDataTable.Rows.Add(dRow)

        dRow = namesDataTable.NewRow()
        dRow("Name") = "Name 3"
        dRow("Date") = New DateTime(2001, 12, 29)
        namesDataTable.Rows.Add(dRow)

        dRow = namesDataTable.NewRow()
        dRow("Name") = "Name 4"
        dRow("Date") = New DateTime(2001, 12, 13)
        namesDataTable.Rows.Add(dRow)

        dRow = namesDataTable.NewRow()
        dRow("Name") = "Name 5"
        dRow("Date") = New DateTime(2001, 12, 21)
        namesDataTable.Rows.Add(dRow)

        namesDataTable.AcceptChanges()
    End Sub 

    Private Sub InitForm()
        Me.Size = New Size(500, 500)
        myGrid.Size = New Size(350, 250)
        myGrid.TabStop = True
        myGrid.TabIndex = 1
        Me.StartPosition = FormStartPosition.CenterScreen
        Me.Controls.Add(myGrid)
    End Sub

    <STAThread()> _
    Public Shared Sub Main()
        Application.Run(New MyForm())
    End Sub 

End Class

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft