Back to Devexpress

GridColumn Class

windowsforms-devexpress-dot-xtragrid-dot-columns.md

latest37.5 KB
Original Source

GridColumn Class

Represents an individual column in Grid Views and Card Views.

Namespace : DevExpress.XtraGrid.Columns

Assembly : DevExpress.XtraGrid.v25.2.dll

NuGet Packages : DevExpress.Win.Grid, DevExpress.Win.Navigation

Declaration

csharp
public class GridColumn :
    Component,
    IAppearanceOwner,
    IXtraSerializableLayoutEx,
    ISupportLookAndFeel,
    IDataColumnInfoProvider,
    ISupportDXSkinColorsEx,
    ISupportDXSkinColors,
    IUnboundColumnTypeProvider,
    IAccessiblePropertiesProvider,
    ISupportAppearanceObjectPropertiesFilter
vb
Public Class GridColumn
    Inherits Component
    Implements IAppearanceOwner,
               IXtraSerializableLayoutEx,
               ISupportLookAndFeel,
               IDataColumnInfoProvider,
               ISupportDXSkinColorsEx,
               ISupportDXSkinColors,
               IUnboundColumnTypeProvider,
               IAccessiblePropertiesProvider,
               ISupportAppearanceObjectPropertiesFilter

The following members return GridColumn objects:

Show 72 links

LibraryRelated API Members
WinForms ControlsCardHitInfo.Column
CellMergeEventArgs.Column
CellValueChangedEventArgs.Column
ColumnEventArgs.Column
ColumnHeaderCustomDrawEventArgs.Column
ColumnView.FocusedColumn
ColumnView.GetNearestCanFocusedColumn(GridColumn)
ColumnView.GetVisibleColumn(Int32)
CustomColumnDataEventArgs.Column
CustomColumnDisplayTextEventArgs.Column
CustomColumnSortEventArgs.Column
CustomFilterDialogEventArgs.Column
CustomizationFormSearchEventArgs.Column
CustomRowCellEventArgs.Column
EditFormValidateEditorEventArgs.Column
FieldHeightEventArgs.Column
FilterPopupEventArgs.Column
FilterPopupExcelParseFilterCriteriaEventArgs.Column
FocusedColumnChangedEventArgs.FocusedColumn
FocusedColumnChangedEventArgs.PrevFocusedColumn
GridCell.Column
GridColumnCollection.Add()
GridColumnCollection.AddField(String)
GridColumnCollection.AddUnbound(String, Type)
GridColumnCollection.AddVisible(String, String)
GridColumnCollection.AddVisible(String)
GridColumnCollection.ColumnByFieldName(String)
GridColumnCollection.ColumnByName(String)
GridColumnCollection.Insert(Int32)
GridColumnCollection.Item[Int32]
GridColumnCollection.Item[String]
GridColumnReadOnlyCollection.Item[Int32]
GridColumnSortInfo.Column
GridFormatRule.Column
GridFormatRule.ColumnApplyTo
GridGroupSummaryItem.ShowInGroupColumnFooter
GridHitInfo.Column
GridMenuItemClickEventArgs.Column
GridView.AddUnboundColumn()
GridView.AddUnboundColumn(String, String, Type)
GridView.AddUnboundColumn(String, String)
GridView.AutoFillColumn
GridView.PressedColumn
GroupSummarySortInfo.GroupColumn
LayoutView.FocusedColumn
LayoutViewFieldCaptionImageEventArgs.Column
LayoutViewHitInfo.Column
RowCellClickEventArgs.Column
RowCellCustomDrawEventArgs.Column
RowCellObjectCustomDrawEventArgs.Column
StyleFormatCondition.Column
TileViewColumns.BackgroundImageColumn
TileViewColumns.CheckedColumn
TileViewColumns.EnabledColumn
TileViewColumns.GroupColumn
TileViewItemElement.Column
UnboundExpressionEditorEventArgs.Column
WinExplorerView.GetColumn(WinExplorerViewFieldType)
WinExplorerViewColumns.CheckBoxColumn
WinExplorerViewColumns.DescriptionColumn
WinExplorerViewColumns.EnabledColumn
WinExplorerViewColumns.ExtraLargeImageColumn
WinExplorerViewColumns.ExtraLargeImageIndexColumn
WinExplorerViewColumns.GroupColumn
WinExplorerViewColumns.LargeImageColumn
WinExplorerViewColumns.LargeImageIndexColumn
WinExplorerViewColumns.MediumImageColumn
WinExplorerViewColumns.MediumImageIndexColumn
WinExplorerViewColumns.SmallImageColumn
WinExplorerViewColumns.SmallImageIndexColumn
WinExplorerViewColumns.TextColumn
XAF: Cross-Platform .NET App UI & Web APIColumnCreatedEventArgs.Column

The following members return GridColumn objects:

Show 72 links

LibraryRelated API Members
WinForms ControlsCardHitInfo.Column
CellMergeEventArgs.Column
CellValueChangedEventArgs.Column
ColumnEventArgs.Column
ColumnHeaderCustomDrawEventArgs.Column
ColumnView.FocusedColumn
ColumnView.GetNearestCanFocusedColumn(GridColumn)
ColumnView.GetVisibleColumn(Int32)
CustomColumnDataEventArgs.Column
CustomColumnDisplayTextEventArgs.Column
CustomColumnSortEventArgs.Column
CustomFilterDialogEventArgs.Column
CustomizationFormSearchEventArgs.Column
CustomRowCellEventArgs.Column
EditFormValidateEditorEventArgs.Column
FieldHeightEventArgs.Column
FilterPopupEventArgs.Column
FilterPopupExcelParseFilterCriteriaEventArgs.Column
FocusedColumnChangedEventArgs.FocusedColumn
FocusedColumnChangedEventArgs.PrevFocusedColumn
GridCell.Column
GridColumnCollection.Add()
GridColumnCollection.AddField(String)
GridColumnCollection.AddUnbound(String, Type)
GridColumnCollection.AddVisible(String, String)
GridColumnCollection.AddVisible(String)
GridColumnCollection.ColumnByFieldName(String)
GridColumnCollection.ColumnByName(String)
GridColumnCollection.Insert(Int32)
GridColumnCollection.Item[Int32]
GridColumnCollection.Item[String]
GridColumnReadOnlyCollection.Item[Int32]
GridColumnSortInfo.Column
GridFormatRule.Column
GridFormatRule.ColumnApplyTo
GridGroupSummaryItem.ShowInGroupColumnFooter
GridHitInfo.Column
GridMenuItemClickEventArgs.Column
GridView.AddUnboundColumn()
GridView.AddUnboundColumn(String, String, Type)
GridView.AddUnboundColumn(String, String)
GridView.AutoFillColumn
GridView.PressedColumn
GroupSummarySortInfo.GroupColumn
LayoutView.FocusedColumn
LayoutViewFieldCaptionImageEventArgs.Column
LayoutViewHitInfo.Column
RowCellClickEventArgs.Column
RowCellCustomDrawEventArgs.Column
RowCellObjectCustomDrawEventArgs.Column
StyleFormatCondition.Column
TileViewColumns.BackgroundImageColumn
TileViewColumns.CheckedColumn
TileViewColumns.EnabledColumn
TileViewColumns.GroupColumn
TileViewItemElement.Column
UnboundExpressionEditorEventArgs.Column
WinExplorerView.GetColumn(WinExplorerViewFieldType)
WinExplorerViewColumns.CheckBoxColumn
WinExplorerViewColumns.DescriptionColumn
WinExplorerViewColumns.EnabledColumn
WinExplorerViewColumns.ExtraLargeImageColumn
WinExplorerViewColumns.ExtraLargeImageIndexColumn
WinExplorerViewColumns.GroupColumn
WinExplorerViewColumns.LargeImageColumn
WinExplorerViewColumns.LargeImageIndexColumn
WinExplorerViewColumns.MediumImageColumn
WinExplorerViewColumns.MediumImageIndexColumn
WinExplorerViewColumns.SmallImageColumn
WinExplorerViewColumns.SmallImageIndexColumn
WinExplorerViewColumns.TextColumn
DashboardGridContext.GetControlColumn(GridColumnBase)

Remarks

GridColumn objects represent columns and card fields in Grid Views and Card Views respectively. Such objects are used to display data from an individual data field. The bound data field is specified by the GridColumn.FieldName property. Settings provided by the GridColumn class also allow you to control how column data is displayed and edited, column header contents, the column’s position and visibility, etc. Note that some of the settings provided are in effect only for columns displayed in Grid Views. For instance, the GridColumn.GroupIndex and GridColumn.SummaryItem properties are in effect for Grid View columns only, as Card Views do not support the grouping and summary features.

You can access a View’s column collection using the ColumnView.Columns property. This property returns an object whose indexer can be used to access individual GridColumn objects. Note also that column objects are Component descendants. This enables you to access columns in code directly by their names.

You don’t need to create column objects manually using the GridColumn class constructor. Columns can be created using methods of the owning column collection (GridColumnCollection class) or by using the ColumnView.PopulateColumns method of the required View.

For additional information regarding columns, refer to the Columns article.

Example

The following example creates a GridControl at runtime and shows how to perform basic customization tasks:

  • Bind the grid to a data source
  • Access the View that displays the underlying data
  • Access columns
  • Assign an in-place editor (a combo box editor) to a column
  • Sort and group data
  • Calculate total and group summaries
  • Create a filter
  • Hide columns and calculate column “best” widths
  • Expand group rows
  • Focus a specific cell
  • Specify DataAnnotation attributes (column display names and data formats) at the data source level

Note

Add the corresponding assemblies to your Windows Forms project.

Read the following topic for information: Redistribution and Deployment of .NET Framework Apps.

csharp
using System;
using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace DXApplication {
    public partial class Form1 : XtraForm {
        public Form1() {
            InitializeComponent();
            this.Load += Form1_Load;
        }
        private void Form1_Load(object sender, EventArgs e) {
            GridControl gridControl1 = new GridControl() {
                Name = "gridControl1",
                Parent = this,
                Dock = DockStyle.Fill
            };
            gridControl1.DataSource = DataHelper.GetData(30);
            // The grid automatically creates columns for the public fields found in the data source. 
            // Calling the gridView1.PopulateColumns method is not required unless gridView1.OptionsBehavior.AutoPopulateColumns is disabled.

            // The grid automatically creates a GridView that displays the underlying data as a two-dimensional table.
            GridView gridView1 = gridControl1.MainView as GridView;

            // Obtain created columns.
            GridColumn colCompany = gridView1.Columns["CompanyName"];
            GridColumn colID = gridView1.Columns["ID"];
            GridColumn colDate = gridView1.Columns["RequiredDate"];
            GridColumn colPayment = gridView1.Columns["Value"];
            GridColumn colProcessed = gridView1.Columns["Processed"];

            // The Company column uses a ComboBox in-place editor that shows a list of available companies.
            RepositoryItemComboBox riComboBox = new RepositoryItemComboBox();
            riComboBox.Items.AddRange(DataHelper.companies);
            gridControl1.RepositoryItems.Add(riComboBox);
            colCompany.ColumnEdit = riComboBox;

            // Hide a column.
            colID.Visible = false;

            // Group and sort data.
            colCompany.GroupIndex = 0;
            colDate.SortIndex = 0;
            colDate.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;

            // Show group columns in the table.
            gridView1.OptionsView.ShowGroupedColumns = true;

            // Expand group rows.
            gridView1.ExpandAllGroups();

            // Apply a filter.
            gridView1.ActiveFilterString = "[RequiredDate]>= #" + DateTime.Today.ToString() + "#";

            // Calculate two total summaries.
            colDate.Summary.Add(SummaryItemType.Count, colDate.FieldName, "Count={0}");
            colDate.Summary.Add(SummaryItemType.Max, colDate.FieldName, "Max={0:d}");
            gridView1.OptionsView.ShowFooter = true;

            // Calculate group summaries.
            GridGroupSummaryItem item = new GridGroupSummaryItem();
            item.FieldName = colCompany.FieldName;
            item.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.GroupSummary.Add(item);

            GridGroupSummaryItem item1 = new GridGroupSummaryItem();
            item1.FieldName = colPayment.FieldName;
            item1.SummaryType = SummaryItemType.Sum;
            item1.DisplayFormat = "group total={0:c2}";
            item1.ShowInGroupColumnFooter = colPayment;
            gridView1.GroupSummary.Add(item1);

            // Forcibly move group footer summaries to positions in group rows under corresponding column headers. 
            gridView1.OptionsBehavior.AlignGroupSummaryInGroupRow = DevExpress.Utils.DefaultBoolean.True;

            // Focus a specific cell.
            gridView1.FocusedRowHandle = 1;
            gridView1.FocusedColumn = colCompany;

            // Optimize column widths.
            colDate.BestFit();
            colProcessed.BestFit();
        }
    }

    public class Record : INotifyPropertyChanged {
        public Record() {
        }
        int id;
        public int ID {
            get { return id; }
            set {
                if(id != value) {
                    id = value;
                    OnPropertyChanged();
                }
            }
        }

        string text;
        [DisplayName("Company")]
        public string CompanyName {
            get { return text; }
            set {
                if(text != value) {
                    if(string.IsNullOrEmpty(value))
                        throw new Exception();
                    text = value;
                    OnPropertyChanged();
                }
            }
        }
        Nullable<decimal> val;
        [DataType(System.ComponentModel.DataAnnotations.DataType.Currency)]
        [DisplayName("Payment")]
        public Nullable<decimal> Value {
            get { return val; }
            set {
                if(val != value) {
                    val = value;
                    OnPropertyChanged();
                }
            }
        }
        DateTime dt;
        [DisplayFormat(DataFormatString = "d")]
        public DateTime RequiredDate {
            get { return dt; }
            set {
                if(dt != value) {
                    dt = value;
                    OnPropertyChanged();
                }
            }
        }
        bool state;
        public bool Processed {
            get { return state; }
            set {
                if(state != value) {
                    state = value;
                    OnPropertyChanged();
                }
            }
        }

        public override string ToString() {
            return string.Format("ID = {0}, Text = {1}", ID, CompanyName);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "") {
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class DataHelper {

        public static string[] companies = new string[] { "Hanari Carnes", "Que Delícia", "Romero y tomillo", "Mère Paillarde",
            "Comércio Mineiro", "Reggiani Caseifici", "Maison Dewey" };
        public static BindingList<Record> GetData(int count) {
            BindingList<Record> records = new BindingList<Record>();
            Random rnd = new Random();
            for(int i = 0; i < count; i++) {
                int n = rnd.Next(10);
                records.Add(new Record() {
                    ID = i + 100,
                    CompanyName = companies[i % companies.Length],
                    RequiredDate = DateTime.Today.AddDays(n - 5),
                    Value = i % 2 == 0 ? (i + 1) * 123 : i * 231,
                    Processed = i % 2 == 0,
                });
            };
            return records;
        }
    }

}
vb
Imports System
Imports DevExpress.ClipboardSource.SpreadsheetML
Imports DevExpress.Data
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Grid
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms

Namespace DXApplication
    Partial Public Class Form1
        Inherits XtraForm

        Public Sub New()
            InitializeComponent()
            AddHandler Me.Load, AddressOf Form1_Load
        End Sub
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim gridControl1 As New GridControl() With {.Name = "gridControl1", .Parent = Me, .Dock = DockStyle.Fill}
            gridControl1.DataSource = DataHelper.GetData(30)
            ' The grid automatically creates columns for the public fields found in the data source. 
            ' Calling the gridView1.PopulateColumns method is not required unless gridView1.OptionsBehavior.AutoPopulateColumns is disabled.

            ' The grid automatically creates a GridView that displays the underlying data as a two-dimensional table.
            Dim gridView1 As GridView = TryCast(gridControl1.MainView, GridView)

            ' Obtain created columns.
            Dim colCompany As GridColumn = gridView1.Columns("CompanyName")
            Dim colID As GridColumn = gridView1.Columns("ID")
            Dim colDate As GridColumn = gridView1.Columns("RequiredDate")
            Dim colPayment As GridColumn = gridView1.Columns("Value")
            Dim colProcessed As GridColumn = gridView1.Columns("Processed")

            ' The Company column uses a ComboBox in-place editor that shows a list of available companies.
            Dim riComboBox As New RepositoryItemComboBox()
            riComboBox.Items.AddRange(DataHelper.companies)
            gridControl1.RepositoryItems.Add(riComboBox)
            colCompany.ColumnEdit = riComboBox

            ' Hide a column.
            colID.Visible = False

            ' Group and sort data.
            colCompany.GroupIndex = 0
            colDate.SortIndex = 0
            colDate.SortOrder = DevExpress.Data.ColumnSortOrder.Descending

            ' Show group columns in the table.
            gridView1.OptionsView.ShowGroupedColumns = True

            ' Expand group rows.
            gridView1.ExpandAllGroups()

            ' Apply a filter.
            gridView1.ActiveFilterString = "[RequiredDate]>= #" & Date.Today.ToString() & "#"

            ' Calculate two total summaries.
            colDate.Summary.Add(SummaryItemType.Count, colDate.FieldName, "Count={0}")
            colDate.Summary.Add(SummaryItemType.Max, colDate.FieldName, "Max={0:d}")
            gridView1.OptionsView.ShowFooter = True

            ' Calculate group summaries.
            Dim item As New GridGroupSummaryItem()
            item.FieldName = colCompany.FieldName
            item.SummaryType = DevExpress.Data.SummaryItemType.Count
            gridView1.GroupSummary.Add(item)

            Dim item1 As New GridGroupSummaryItem()
            item1.FieldName = colPayment.FieldName
            item1.SummaryType = SummaryItemType.Sum
            item1.DisplayFormat = "group total={0:c2}"
            item1.ShowInGroupColumnFooter = colPayment
            gridView1.GroupSummary.Add(item1)

            ' Forcibly move group footer summaries to positions in group rows under corresponding column headers. 
            gridView1.OptionsBehavior.AlignGroupSummaryInGroupRow = DevExpress.Utils.DefaultBoolean.True

            ' Focus a specific cell.
            gridView1.FocusedRowHandle = 1
            gridView1.FocusedColumn = colCompany

            ' Optimize column widths.
            colDate.BestFit()
            colProcessed.BestFit()
        End Sub
    End Class

    Public Class Record
        Implements INotifyPropertyChanged

        Public Sub New()
        End Sub

        Private id_Renamed As Integer
        Public Property ID() As Integer
            Get
                Return id_Renamed
            End Get
            Set(ByVal value As Integer)
                If id_Renamed <> value Then
                    id_Renamed = value
                    OnPropertyChanged()
                End If
            End Set
        End Property

        Private text As String
        <DisplayName("Company")>
        Public Property CompanyName() As String
            Get
                Return text
            End Get
            Set(ByVal value As String)
                If text <> value Then
                    If String.IsNullOrEmpty(value) Then
                        Throw New Exception()
                    End If
                    text = value
                    OnPropertyChanged()
                End If
            End Set
        End Property
        Private val? As Decimal
        <DataType(System.ComponentModel.DataAnnotations.DataType.Currency), DisplayName("Payment")>
        Public Property Value() As Decimal?
            Get
                Return val
            End Get
            Set(ByVal value? As Decimal)
                If Not val.Equals(value) Then
                    val = value
                    OnPropertyChanged()
                End If
            End Set
        End Property
        Private dt As Date
        <DisplayFormat(DataFormatString := "d")>
        Public Property RequiredDate() As Date
            Get
                Return dt
            End Get
            Set(ByVal value As Date)
                If dt <> value Then
                    dt = value
                    OnPropertyChanged()
                End If
            End Set
        End Property
        Private state As Boolean
        Public Property Processed() As Boolean
            Get
                Return state
            End Get
            Set(ByVal value As Boolean)
                If state <> value Then
                    state = value
                    OnPropertyChanged()
                End If
            End Set
        End Property

        Public Overrides Function ToString() As String
            Return String.Format("ID = {0}, Text = {1}", ID, CompanyName)
        End Function

        Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
        Protected Sub OnPropertyChanged(Optional <CallerMemberName> ByVal propertyName As String = "")
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
        End Sub
    End Class

    Public Class DataHelper

        Public Shared companies() As String = { "Hanari Carnes", "Que Delícia", "Romero y tomillo", "Mère Paillarde", "Comércio Mineiro", "Reggiani Caseifici", "Maison Dewey" }
        Public Shared Function GetData(ByVal count As Integer) As BindingList(Of Record)
            Dim records As New BindingList(Of Record)()
            Dim rnd As New Random()
            For i As Integer = 0 To count - 1
                Dim n As Integer = rnd.Next(10)
                records.Add(New Record() With {.ID = i + 100, .CompanyName = companies(i Mod companies.Length), .RequiredDate = Date.Today.AddDays(n - 5), .Value = If(i Mod 2 = 0, (i + 1) * 123, i * 231), .Processed = i Mod 2 = 0})
            Next i
            Return records
        End Function
    End Class

End Namespace

Inheritance

Object MarshalByRefObject Component GridColumn LayoutViewColumn

BandedGridColumn

See Also

GridColumn Members

GridColumnCollection

Columns

Item

Column

DevExpress.XtraGrid.Columns Namespace