Skip to main content

GridControl Class

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

Namespace: DevExpress.XtraGrid

Assembly: DevExpress.XtraGrid.v24.2.dll

Declaration

public class GridControl :
    EditorContainer,
    IScrollBarAnnotationsOwner<ScrollAnnotationKind>,
    IScrollBarOwner,
    IPrintableEx,
    IPrintable,
    IBasePrintable,
    IPrintHeaderFooter,
    INavigatableControl,
    IToolTipControlClient,
    IDXManagerPopupMenu,
    IViewController,
    IFilteredComponent,
    IFilteredComponentBase,
    IBoundControl,
    ISupportXtraSerializer,
    IGestureClient,
    IGuideDescription,
    ISearchControlColumnsClient,
    ISearchControlClient,
    ILogicalOwner,
    ISupportFilterCriteriaDisplayStyle,
    IChildAccessibleInfoProvider

Remarks

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

WinForms Data Grid with GridView

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.

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;
        }
    }
}

WinForms Data Grid - Bind to Data, DevExpress

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:

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;
        }
    }
}

WinForms Data Grid assign GridView to GridControl in code

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:

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;

        }
    }
}

WinForms Data Grid - Create Grid Columns, DevExpress

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.

void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["FirstName"].Group();
}

WinForms Data Grid - Grouping, DevExpress

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.

void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["FirstName"].GroupIndex = 0;
    gridView1.Columns["BirthDate"].GroupIndex = 1;
    gridView1.Columns["City"].GroupIndex = 2;
}

WinForms Data Grid - Group by Multiple Columns, DevExpress

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):

using DevExpress.Data;
void Form1_Shown(object sender, EventArgs e) {
    gridView1.Columns["LastName"].SortOrder = ColumnSortOrder.Ascending;
}

WinForms Data Grid - Data Sorting, DevExpress

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.

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;
}

WinForms Data Grid - Sort by Multiple Columns, DevExpress

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”:

void Form1_Shown(object sender, EventArgs e) {
    gridView1.ActiveFilterString = "[LastName] LIKE 'D%'";
}

WinForms Data Grid apply filter in code

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:

// 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;

WinForms Data Grid create and display summary in code

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.

Data Grid - Date Edit In-Place Editor

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.

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.

    // 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;

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.

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

WinForms Data Grid change focused cell appearance

Example 2: Highlight the active editor

This example changes the background color of the active editor.

gridView1.ShownEditor += (s, e) => {
    GridView view = s as GridView;
    view.ActiveEditor.BackColor = Color.DodgerBlue;
};

WinForms Data Grid change active editor appearance

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.

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;
}

WinForms Data Grid change appearance of cells in specific column

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

See Also