Back to Devexpress

GridControl Class

windowsforms-devexpress-dot-xtragrid.md

latest34.5 KB
Original Source

GridControl Class

Displays data from a data source as a table, cards, tiles, or in other formats.

Namespace : DevExpress.XtraGrid

Assembly : DevExpress.XtraGrid.v25.2.dll

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

Declaration

csharp
[DXLicenseWinForms]
public class GridControl :
    EditorContainer,
    IScrollBarAnnotationsOwner<ScrollAnnotationKind>,
    IScrollBarOwner,
    IPrintableEx,
    IPrintable,
    IBasePrintable,
    IPrintingTarget,
    IPrintHeaderFooter,
    INavigatableControl,
    IToolTipControlClient,
    IDXManagerPopupMenu,
    IViewController,
    IFilteredComponent,
    IFilteredComponentBase,
    IBoundControl,
    ISupportJsonXtraSerializer,
    ISupportXtraSerializer,
    IGestureClient,
    IGuideDescription,
    ISearchControlColumnsClient,
    ISearchControlClient,
    ILogicalOwner,
    ISupportFilterCriteriaDisplayStyle,
    IChildAccessibleInfoProvider
vb
<DXLicenseWinForms>
Public Class GridControl
    Inherits EditorContainer
    Implements IScrollBarAnnotationsOwner(Of ScrollAnnotationKind),
               IScrollBarOwner,
               IPrintableEx,
               IPrintable,
               IBasePrintable,
               IPrintingTarget,
               IPrintHeaderFooter,
               INavigatableControl,
               IToolTipControlClient,
               IDXManagerPopupMenu,
               IViewController,
               IFilteredComponent,
               IFilteredComponentBase,
               IBoundControl,
               ISupportJsonXtraSerializer,
               ISupportXtraSerializer,
               IGestureClient,
               IGuideDescription,
               ISearchControlColumnsClient,
               ISearchControlClient,
               ILogicalOwner,
               ISupportFilterCriteriaDisplayStyle,
               IChildAccessibleInfoProvider

The following members return GridControl objects:

LibraryRelated API Members
WinForms ControlsBaseView.GridControl
GridSplitContainer.Grid
GridSplitContainer.SplitChildGrid
XAF: Cross-Platform .NET App UI & Web APIWinColumnsListEditor.Grid

The following members return GridControl objects:

LibraryRelated API Members
WinForms ControlsBaseView.GridControl
GridSplitContainer.Grid
GridSplitContainer.SplitChildGrid
DashboardDashboardItemControlEventArgs.GridControl
DataInspectorFormClosingEventArgs.AggregatedDataGrid
DataInspectorFormClosingEventArgs.RawDataGrid
DataInspectorFormLoadEventArgs.AggregatedDataGrid
DataInspectorFormLoadEventArgs.RawDataGrid

Remarks

The Data Grid (GridControl) is a container for Views that can display data from a bound list, table, or collection.

The following help topics give a detailed overview of Data Grid features:

Watch Video: Getting Started Run Demo

Bind to Data

Use the following API to assign a data source to the GridControl:

|

API

|

Description

| | --- | --- | |

DataSource

|

Gets or sets the grid control’s data source.

| |

DataMember

|

Gets or sets a sub-list of the data source whose data is supplied for the grid control’s main View.

|

The following code snippet creates a GridControl and binds it to the Employees table of the Northwind database. The GridControl automatically creates columns for data fields.

csharp
using System;
using System.Windows.Forms;
using DevExpress.XtraGrid;

namespace DXApplication {
    public partial class Form1 : DevExpress.XtraEditors.XtraForm {
        GridControl gridControl1;
        public Form1() {
            InitializeComponent();
            gridControl1 = new GridControl();
            gridControl1.Dock = DockStyle.Fill;
            this.Controls.Add(gridControl1);
        }

        void Form1_Load(object sender, EventArgs e) {
            employeesTableAdapter.Fill(nwindDataSet.Employees);
            gridControl1.DataSource = employeesBindingSource;
        }
    }
}
vb
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraGrid

Namespace DXApplication
    Partial Public Class Form1
        Inherits DevExpress.XtraEditors.XtraForm

        Private gridControl1 As GridControl
        Public Sub New()
            InitializeComponent()
            gridControl1 = New GridControl()
            gridControl1.Dock = DockStyle.Fill
            Me.Controls.Add(gridControl1)
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            employeesTableAdapter.Fill(nwindDataSet.Employees)
            gridControl1.DataSource = employeesBindingSource
        End Sub
    End Class
End Namespace

Tip

Read the following help topic for a list of supported data sources and step-by-step tutorials: Data Binding.

Read the following step-by-step-tutorials for information on how to bind to specific data types:

Assign a View

DevExpress GridControl uses Views to display data from a data source. Views specify the presentation and layout of data records and fields. Views introduce a comprehensive set of edit, display, behavior, and appearance options.

GridControl ships with the following data views:

GridControl uses a GridView as the default View. Use the MainView property to specify the View. The following code snippet specifies a CardView as the main View:

csharp
using System;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Card;

namespace DXApplication2 {
    public partial class Form1 : DevExpress.XtraEditors.XtraForm {
        GridControl gridControl1;
        public Form1() {
            InitializeComponent();
            gridControl1 = new GridControl() { Dock = DockStyle.Fill };
            gridControl1.MainView = new CardView();
            this.Controls.Add(gridControl1);
        }

        void Form1_Load(object sender, EventArgs e) {
            employeesTableAdapter.Fill(nwindDataSet.Employees);
            gridControl1.DataSource = employeesBindingSource;
        }
    }
}
vb
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Card

Namespace DXApplication2
    Partial Public Class Form1
        Inherits DevExpress.XtraEditors.XtraForm

        Private gridControl1 As GridControl
        Public Sub New()
            InitializeComponent()
            gridControl1 = New GridControl() With {.Dock = DockStyle.Fill}
            gridControl1.MainView = New CardView()
            Me.Controls.Add(gridControl1)
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            employeesTableAdapter.Fill(nwindDataSet.Employees)
            gridControl1.DataSource = employeesBindingSource
        End Sub
    End Class
End Namespace

Use the following API to assign and access Views:

|

API

|

Description

| | --- | --- | |

MainView

|

Gets or sets the View that displays data at the top hierarchy level.

| |

CreateView(String)

|

Creates a View of the specified type.

| |

Views

|

Gets the collection of Views currently displayed by the grid control.

| |

ViewCollection

|

Provides access to the collection of Views in the grid’s View repository.

|

Tip

Read the following help topic for information on how to change the view and customize view settings at design time: Select a View.

Create Columns

The View holds grid columns in the Columns collection. Use the Columns collection to add, remove, and arrange grid columns. The View automatically creates grid columns for all bound data fields if the Columns collection is empty and the AutoPopulateColumns option is enabled.

Read the following help topic for information on how to manage grid columns at design time: Access and Customize Views and Columns at Design Time.

Use the following API to manage grid columns:

|

API

|

Description

| | --- | --- | |

Columns

|

Provides access to the collection of columns available for display within the View.

| |

OptionsBehavior.AutoPopulateColumns

|

Gets or sets whether to create columns automatically for all fields in the underlying data source (when binding the grid and the View does not contain any columns).

| |

PopulateColumns()

|

Clears the Columns collection and creates columns for all fields in the bound data source.

|

The following code snippet creates “First Name” and “Last Name” columns:

csharp
using System;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;

namespace DXApplication {
    public partial class Form1 : DevExpress.XtraEditors.XtraForm {
        GridControl gridControl1;
        public Form1() {
            InitializeComponent();
            gridControl1 = new GridControl() { Dock = DockStyle.Fill };
            // Force the GridControl to initialize its settings.
            gridControl1.ForceInitialize();
            // Add 'FirstName' and 'LastName' columns.
            (gridControl1.MainView as ColumnView).Columns.AddRange(
                new GridColumn[]{
                    new GridColumn() { Name = "colFirstName", FieldName = "FirstName", Visible = true },
                    new GridColumn() { Name = "colLastName", FieldName = "LastName", Visible = true }
                }
            );
            this.Controls.Add(gridControl1);
        }

        void Form1_Load(object sender, EventArgs e) {
            employeesTableAdapter.Fill(nwindDataSet.Employees);
            // Bind the GridControl to data.
            gridControl1.DataSource = employeesBindingSource;

        }
    }
}
vb
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Base

Namespace DXApplication
    Partial Public Class Form1
        Inherits DevExpress.XtraEditors.XtraForm

        Private gridControl1 As GridControl
        Public Sub New()
            InitializeComponent()
            gridControl1 = New GridControl() With {.Dock = DockStyle.Fill}
            ' Force the GridControl to initialize its settings.
            gridControl1.ForceInitialize()
            ' Add 'FirstName' and 'LastName' columns.
            TryCast(gridControl1.MainView, ColumnView).Columns.AddRange(New GridColumn(){
                New GridColumn() With {
                    .Name = "colFirstName",
                    .FieldName = "FirstName",
                    .Visible = True
                },
                New GridColumn() With {
                    .Name = "colLastName",
                    .FieldName = "LastName",
                    .Visible = True
                }
            })
            Me.Controls.Add(gridControl1)
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            employeesTableAdapter.Fill(nwindDataSet.Employees)
            ' Bind the GridControl to data.
            gridControl1.DataSource = employeesBindingSource

        End Sub
    End Class
End Namespace

See the following help topic for additional information and examples: Working with Columns in Code.

Tip

GridControl supports unbound columns. Refer to the following help topics for information:

Data Shaping and Aggregation

Grouping

The grouping feature combines data rows with identical column values into groups. This feature is supported in the Grid View and Banded Grid Views.

Watch Video Run Demo

Refer to the following help topic for more information: Grouping.

Example 1: Group by a column

This example groups data by the “First Name” column.

csharp
void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["FirstName"].Group();
}
vb
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
    gridView1.Columns("FirstName").Group()
End Sub

Example 2: Group by multiple columns

This example groups data by three columns. The GroupIndex property value specifies the order in which columns are grouped.

csharp
void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["FirstName"].GroupIndex = 0;
    gridView1.Columns["BirthDate"].GroupIndex = 1;
    gridView1.Columns["City"].GroupIndex = 2;
}
vb
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
    gridView1.Columns("FirstName").GroupIndex = 0
    gridView1.Columns("BirthDate").GroupIndex = 1
    gridView1.Columns("City").GroupIndex = 2
End Sub

Sorting

The sorting feature reorders data rows to display values of specific column(s) in ascending, descending, or custom order.

Watch Video Run Demo

Refer to the following help topic for more information: Sorting.

Example 1: Sort by a column

This example sorts the “Last Name” column in ascending order (alphabetically):

csharp
using DevExpress.Data;
void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["LastName"].SortOrder = ColumnSortOrder.Ascending;
}
vb
Imports DevExpress.Data
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
    gridView1.Columns("LastName").SortOrder = ColumnSortOrder.Ascending
End Sub

Example 2: Sort by multiple columns

This example sorts data by values in the “Last Name” column. If the “Last Name” column contains identical values, data is sorted further by the “City” column.

csharp
using DevExpress.Data;

void Form1_Shown(object sender, EventArgs e) {
    GridColumn colName = gridView1.Columns["LastName"];
    GridColumn colCity = gridView1.Columns["City"];
    colName.SortIndex = 0;
    colName.SortOrder = ColumnSortOrder.Ascending;
    colCity.SortIndex = 1;
    colCity.SortOrder = ColumnSortOrder.Descending;
}
vb
Imports DevExpress.Data

Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
    Dim ColName As GridColumn = gridView1.Columns("LastName")
    Dim ColCity As GridColumn = gridView1.Columns("City")
    ColName.SortIndex = 0
    ColCity.SortIndex = 1
    ColName.SortOrder = ColumnSortOrder.Ascending
    ColCity.SortOrder = ColumnSortOrder.Descending
End Sub

Filtering

The WinForms Grid Control includes a comprehensive set of filter and custom query options. When a filter is applied, the View displays only records that meet the current filter criteria.

Watch Video Run Demo

The following code snippet filters the grid to display only data rows in which the “Last Name” column value begins with “D”:

csharp
void Form1_Shown(object sender, EventArgs e) {
    gridView1.ActiveFilterString = "[LastName] LIKE 'D%'";
}
vb
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
      gridView1.ActiveFilterString = "[LastName] LIKE 'D%'"
End Sub

Refer to the following help topic for more information: Filter and Search.

Data Aggregation and Summaries

Summaries utilize aggregate functions to display summary information: total record count, minimum values, etc.

Watch Video Run Demo

The following code snippet creates a total summary item:

csharp
// Create a summary item.
GridColumnSummaryItem siTotal = new GridColumnSummaryItem() {
    SummaryType = DevExpress.Data.SummaryItemType.Count,
    DisplayFormat = "{0} records"
};
// Associate the summary item with the 'FirstName' column.
gridView1.Columns["FirstName"].Summary.Add(siTotal);
// Display the GridView's footer.
gridView1.OptionsView.ShowFooter = true;
vb
' Create a summary item.
Dim siTotal As New GridColumnSummaryItem() With {
    .SummaryType = DevExpress.Data.SummaryItemType.Count,
    .DisplayFormat = "{0} records"
}
' Associate the summary item in the 'FirstName' column.
gridView1.Columns("FirstName").Summary.Add(siTotal)
' Display the GridView's footer.
gridView1.OptionsView.ShowFooter = True

Refer to the following help topic for more information and examples: Summaries.

Data Editing

The Grid Control allows you to incorporate various data editors within grid cells. Users can edit cell values in-place or in a separate edit form.

Run Demo: Cell Editors

The following table lists common editing-related tasks and corresponding help topics:

|

Task

|

Help topic

| | --- | --- | |

Get/set cell values in code

|

Modify Cell Values in Code

| |

Assign cell editors

|

Cell Editors

| |

Add/remove rows

|

Add and Remove Rows

| |

Edit data in a separate form

|

Edit Form

| |

Error-free user input

|

Manage User Input

| |

Post changes to the database

|

Post Data to an Underlying Data Source

| |

Edit an unbound column

|

Editable Unbound Columns with Custom Data

|

Example 1: Change the focused cell value

This example changes the value of the focused cell.

csharp
gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.FocusedColumn, "New Value");
//or
gridView1.SetFocusedValue("New Value");
vb
gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.FocusedColumn, "New Value")
'or
gridView1.SetFocusedValue("New Value")

Example 2: Assign a cell editor to a column

This example creates a ToggleSwitch repository item and assigns it to the “Mark” column.

csharp
// Creates a 'ToggleSwitch' repository item.            
    RepositoryItemToggleSwitch edit = new RepositoryItemToggleSwitch();
    // Adds the repository item to the grid's RepositoryItems collection. 
    gridControl.RepositoryItems.Add(edit);
    // Assigns the repository item to the 'Mark' column.
    gridView.Columns["Mark"].ColumnEdit = edit;
vb
' Creates a 'ToggleSwitch' repository item.           
    Dim edit As New RepositoryItemToggleSwitch()
    ' Adds the repository item to the grid's RepositoryItems collection.
    gridControl.RepositoryItems.Add(edit)
    ' Assigns the repository item to the 'Mark' column.
    gridView.Columns("Mark").ColumnEdit = edit

Refer to the following help topic for more information: Edit Data. Create Cell Editors. Validate User Input.

Master-Detail Presentation

The Grid Control supports master-detail data presentation with any number of nesting levels and any number of details at each level. Detail views can display any type of information.

Run Demo: Master-Detail Watch Video

Design Time

Read the following help topic for information on how to create and manage master-detail relationships at design time: Master-Detail Relationships.

In Code

The following help topic describes how to create and manage master-detail relationships in code: Working with Master-Detail Relationships in Code.

Appearance

Design Time

The following help topics describe how to change the appearance of various Grid elements at design time:

In Code

Read the following help topic for a list of related API and examples: Appearance and Conditional Formatting.

Example 1: Change the focused cell's appearance

This example changes the background color and text color of the focused cell.

csharp
gridView1.Appearance.FocusedCell.BackColor = DXSkinColors.FillColors.Warning;
gridView1.Appearance.FocusedCell.ForeColor = Color.Blue;
vb
gridView1.Appearance.FocusedCell.BackColor = DXSkinColors.FillColors.Warning
gridView1.Appearance.FocusedCell.ForeColor = Color.Blue

Example 2: Highlight the active editor

This example changes the background color of the active editor.

csharp
gridView1.ShownEditor += (s, e) => {
    GridView view = s as GridView;
    view.ActiveEditor.BackColor = Color.DodgerBlue;
};
vb
AddHandler gridView.ShownEditor, Sub(s, e)
    Dim view As GridView = TryCast(s, GridView)
    view.ActiveEditor.BackColor = Color.DodgerBlue
End Sub

Example 3: Highlight cells of a specific column

This example changes text alignment and sets a blue text color for cells in the “First Name” column.

csharp
using DevExpress.Utils;

void Form1_Shown(object sender, EventArgs e) {
        gridView1.Columns["FirstName"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
        gridView1.Columns["FirstName"].AppearanceCell.Options.UseTextOptions = true;
        gridView1.Columns["FirstName"].AppearanceCell.ForeColor = Color.Blue;
}
vb
Imports DevExpress.Utils

Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs)
      gridView1.Columns("FirstName").AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center
      gridView1.Columns("FirstName").AppearanceCell.Options.UseTextOptions = True
      gridView1.Columns("FirstName").AppearanceCell.ForeColor = Color.Blue
End Sub

Export and Printing

The following help topics describe different aspects of print and export:

Examples

Get More Information

More examples and articles on this product can be found on our website. Access our Support Center to find related articles in our online Knowledge Base.

Implements

IPrintable

Inheritance

Object MarshalByRefObject Component Control EditorContainer GridControl

See Also

GridControl Members

Get Started With Data Grid and Views

Data Binding

Data Editing and Validation

Master-Detail Relationships

DevExpress.XtraGrid Namespace