Edit

Share via


DataGridColumnStyle Class

Definition

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

C#
public abstract class DataGridColumnStyle : System.ComponentModel.Component, System.Windows.Forms.IDataGridColumnStyleEditingNotificationService
Inheritance
DataGridColumnStyle
Derived
Implements

Examples

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

C#
using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;

// This example shows how to create your own column style that
// hosts a control, in this case, a DateTimePicker.
public class DataGridTimePickerColumn : DataGridColumnStyle
{
    private CustomDateTimePicker customDateTimePicker1 = 
        new CustomDateTimePicker();

    // The isEditing field tracks whether or not the user is
    // editing data with the hosted control.
    private bool isEditing;

    public DataGridTimePickerColumn() : base()
    {
        customDateTimePicker1.Visible = false;
    }

    protected override void Abort(int rowNum)
    {
        isEditing = false;
        customDateTimePicker1.ValueChanged -=
            new EventHandler(TimePickerValueChanged);
        Invalidate();
    }

    protected override bool Commit
        (CurrencyManager dataSource, int rowNum)
    {
        customDateTimePicker1.Bounds = Rectangle.Empty;

        customDateTimePicker1.ValueChanged -=
            new EventHandler(TimePickerValueChanged);

        if (!isEditing)
            return true;

        isEditing = false;

        try
        {
            DateTime value = customDateTimePicker1.Value;
            SetColumnValueAtRow(dataSource, rowNum, value);
        }
        catch (Exception)
        {
            Abort(rowNum);
            return false;
        }

        Invalidate();
        return true;
    }

    protected override void Edit(
        CurrencyManager source,
        int rowNum,
        Rectangle bounds,
        bool readOnly,
        string displayText,
        bool cellIsVisible)
    {
        DateTime value = (DateTime)
            GetColumnValueAtRow(source, rowNum);
        if (cellIsVisible)
        {
            customDateTimePicker1.Bounds = new Rectangle
                (bounds.X + 2, bounds.Y + 2,
                bounds.Width - 4, bounds.Height - 4);
            customDateTimePicker1.Value = value;
            customDateTimePicker1.Visible = true;
            customDateTimePicker1.ValueChanged +=
                new EventHandler(TimePickerValueChanged);
        }
        else
        {
            customDateTimePicker1.Value = value;
            customDateTimePicker1.Visible = false;
        }

        if (customDateTimePicker1.Visible)
            DataGridTableStyle.DataGrid.Invalidate(bounds);

        customDateTimePicker1.Focus();
    }

    protected override Size GetPreferredSize(
        Graphics g,
        object value)
    {
        return new Size(100, customDateTimePicker1.PreferredHeight + 4);
    }

    protected override int GetMinimumHeight()
    {
        return customDateTimePicker1.PreferredHeight + 4;
    }

    protected override int GetPreferredHeight(Graphics g,
        object value)
    {
        return customDateTimePicker1.PreferredHeight + 4;
    }

    protected override void Paint(Graphics g,
        Rectangle bounds,
        CurrencyManager source,
        int rowNum)
    {
        Paint(g, bounds, source, rowNum, false);
    }

    protected override void Paint(
        Graphics g,
        Rectangle bounds,
        CurrencyManager source,
        int rowNum,
        bool alignToRight)
    {
        Paint(
            g, bounds,
            source,
            rowNum,
            Brushes.Red,
            Brushes.Blue,
            alignToRight);
    }

    protected override void Paint(
        Graphics g,
        Rectangle bounds,
        CurrencyManager source,
        int rowNum,
        Brush backBrush,
        Brush foreBrush,
        bool alignToRight)
    {
        DateTime date = (DateTime)
            GetColumnValueAtRow(source, rowNum);
        Rectangle rect = bounds;
        g.FillRectangle(backBrush, rect);
        rect.Offset(0, 2);
        rect.Height -= 2;
        g.DrawString(date.ToString("d"),
            this.DataGridTableStyle.DataGrid.Font,
            foreBrush, rect);
    }

    protected override void SetDataGridInColumn(DataGrid value)
    {
        base.SetDataGridInColumn(value);
        if (customDateTimePicker1.Parent != null)
        {
            customDateTimePicker1.Parent.Controls.Remove
                (customDateTimePicker1);
        }
        if (value != null)
        {
            value.Controls.Add(customDateTimePicker1);
        }
    }

    private void TimePickerValueChanged(object sender, EventArgs e)
    {
        // Remove the handler to prevent it from being called twice in a row.
        customDateTimePicker1.ValueChanged -=
            new EventHandler(TimePickerValueChanged);
        this.isEditing = true;
        base.ColumnStartedEditing(customDateTimePicker1);
    }
}

public class CustomDateTimePicker : DateTimePicker
{
    protected override bool ProcessKeyMessage(ref Message m)
    {
        // Keep all the keys for the DateTimePicker.
        return ProcessKeyEventArgs(ref m);
    }
}

public class MyForm : Form
{
    private DataTable namesDataTable;
    private DataGrid grid = new DataGrid();
    public MyForm() : base()
    {
        InitForm();

        namesDataTable = new DataTable("NamesTable");
        namesDataTable.Columns.Add(new DataColumn("Name"));
        DataColumn dateColumn = new DataColumn
            ("Date", typeof(DateTime));
        dateColumn.DefaultValue = DateTime.Today;
        namesDataTable.Columns.Add(dateColumn);
        DataSet namesDataSet = new DataSet();
        namesDataSet.Tables.Add(namesDataTable);
        grid.DataSource = namesDataSet;
        grid.DataMember = "NamesTable";
        AddGridStyle();
        AddData();
    }

    private void AddGridStyle()
    {
        DataGridTableStyle myGridStyle = new DataGridTableStyle();
        myGridStyle.MappingName = "NamesTable";

        DataGridTextBoxColumn nameColumnStyle =
            new DataGridTextBoxColumn();
        nameColumnStyle.MappingName = "Name";
        nameColumnStyle.HeaderText = "Name";
        myGridStyle.GridColumnStyles.Add(nameColumnStyle);

        DataGridTimePickerColumn timePickerColumnStyle =
            new DataGridTimePickerColumn();
        timePickerColumnStyle.MappingName = "Date";
        timePickerColumnStyle.HeaderText = "Date";
        timePickerColumnStyle.Width = 100;
        myGridStyle.GridColumnStyles.Add(timePickerColumnStyle);

        grid.TableStyles.Add(myGridStyle);
    }

    private void AddData()
    {

        DataRow dRow = namesDataTable.NewRow();
        dRow["Name"] = "Name 1";
        dRow["Date"] = new DateTime(2001, 12, 01);
        namesDataTable.Rows.Add(dRow);

        dRow = namesDataTable.NewRow();
        dRow["Name"] = "Name 2";
        dRow["Date"] = new DateTime(2001, 12, 04);
        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();
    }

    private void InitForm()
    {
        this.Size = new Size(500, 500);
        grid.Size = new Size(350, 250);
        grid.TabStop = true;
        grid.TabIndex = 1;
        this.StartPosition = FormStartPosition.CenterScreen;
        this.Controls.Add(grid);
    }
 
    [STAThread]
    public static void Main()
    {
        Application.Run(new MyForm());
    }
}

Remarks

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

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(Int32), Commit(CurrencyManager, Int32), Edit(CurrencyManager, Int32, Rectangle, Boolean), and Paint(Graphics, Rectangle, CurrencyManager, Int32) (twice).

Constructors

DataGridColumnStyle()

In a derived class, initializes a new instance of the DataGridColumnStyle class.

DataGridColumnStyle(PropertyDescriptor)

Initializes a new instance of the DataGridColumnStyle class with the specified PropertyDescriptor.

Properties

Alignment

Gets or sets the alignment of text in a column.

CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container

Gets the IContainer that contains the Component.

(Inherited from Component)
DataGridTableStyle

Gets the DataGridTableStyle for the column.

DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
FontHeight

Gets the height of the column's font.

HeaderAccessibleObject

Gets the AccessibleObject for the column.

HeaderText

Gets or sets the text of the column header.

MappingName

Gets or sets the name of the data member to map the column style to.

NullText

Gets or sets the text that is displayed when the column contains null.

PropertyDescriptor

Gets or sets the PropertyDescriptor that determines the attributes of data displayed by the DataGridColumnStyle.

ReadOnly

Gets or sets a value indicating whether the data in the column can be edited.

Site

Gets or sets the ISite of the Component.

(Inherited from Component)
Width

Gets or sets the width of the column.

Methods

Abort(Int32)

When overridden in a derived class, initiates a request to interrupt an edit procedure.

BeginUpdate()

Suspends the painting of the column until the EndUpdate() method is called.

CheckValidDataSource(CurrencyManager)

Throws an exception if the DataGrid does not have a valid data source, or if this column is not mapped to a valid property in the data source.

ColumnStartedEditing(Control)

Informs the DataGrid that the user has begun editing the column.

Commit(CurrencyManager, Int32)

When overridden in a derived class, initiates a request to complete an editing procedure.

ConcedeFocus()

Notifies a column that it must relinquish the focus to the control it is hosting.

CreateHeaderAccessibleObject()

Gets the AccessibleObject for the column.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Edit(CurrencyManager, Int32, Rectangle, Boolean, String, Boolean)

When overridden in a deriving class, prepares a cell for editing.

Edit(CurrencyManager, Int32, Rectangle, Boolean, String)

Prepares the cell for editing using the specified CurrencyManager, row number, and Rectangle parameters.

Edit(CurrencyManager, Int32, Rectangle, Boolean)

Prepares a cell for editing.

EndUpdate()

Resumes the painting of columns suspended by calling the BeginUpdate() method.

EnterNullValue()

Enters a Value into the column.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetColumnValueAtRow(CurrencyManager, Int32)

Gets the value in the specified row from the specified CurrencyManager.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetMinimumHeight()

When overridden in a derived class, gets the minimum height of a row.

GetPreferredHeight(Graphics, Object)

When overridden in a derived class, gets the height used for automatically resizing columns.

GetPreferredSize(Graphics, Object)

When 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.

GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
Invalidate()

Redraws the column and causes a paint message to be sent to the control.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Paint(Graphics, Rectangle, CurrencyManager, Int32, Boolean)

When overridden in a derived class, paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, and alignment.

Paint(Graphics, Rectangle, CurrencyManager, Int32, Brush, Brush, Boolean)

Paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, background color, foreground color, and alignment.

Paint(Graphics, Rectangle, CurrencyManager, Int32)

Paints the DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, and row number.

ReleaseHostedControl()

Allows the column to free resources when the control it hosts is not needed.

ResetHeaderText()

Resets the HeaderText to its default value, null.

SetColumnValueAtRow(CurrencyManager, Int32, Object)

Sets the value in a specified row with the value from a specified CurrencyManager.

SetDataGrid(DataGrid)

Sets the DataGrid control that this column belongs to.

SetDataGridInColumn(DataGrid)

Sets the DataGrid for the column.

ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component)
UpdateUI(CurrencyManager, Int32, String)

Updates the value of a specified row with the given text.

Events

AlignmentChanged

Occurs when the Alignment property value changes.

Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
FontChanged

Occurs when the column's font changes.

HeaderTextChanged

Occurs when the HeaderText property value changes.

MappingNameChanged

Occurs when the MappingName value changes.

NullTextChanged

Occurs when the NullText value changes.

PropertyDescriptorChanged

Occurs when the PropertyDescriptor property value changes.

ReadOnlyChanged

Occurs when the ReadOnly property value changes.

WidthChanged

Occurs when the Width property value changes.

Explicit Interface Implementations

IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control)

Informs the DataGrid control that the user has begun editing the column.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0

See also