Share via


How to: Change the Order of Columns in the Windows Forms DataGridView Control

When you use a DataGridView to display data from a data source, the columns in the data source's schema sometimes do not appear in the order you would like to display them. You can change the displayed order of the columns by using the DisplayIndex property of the DataGridViewColumn class.

The following code example repositions some of the columns automatically generated when binding to the Customers table in the Northwind sample database. For more information about how to bind the DataGridView control to a database table, see How to: Bind Data to the Windows Forms DataGridView Control.

There is support for this task in Visual Studio. How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer
How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer
How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer
How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer

Example

Private Sub AdjustColumnOrder()

    With customersDataGridView
        .Columns("CustomerID").Visible = False
        .Columns("ContactName").DisplayIndex = 0
        .Columns("ContactTitle").DisplayIndex = 1
        .Columns("City").DisplayIndex = 2
        .Columns("Country").DisplayIndex = 3
        .Columns("CompanyName").DisplayIndex = 4
    End With

End Sub
private void AdjustColumnOrder()
{
    customersDataGridView.Columns["CustomerID"].Visible = false;
    customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
    customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
    customersDataGridView.Columns["City"].DisplayIndex = 2;
    customersDataGridView.Columns["Country"].DisplayIndex = 3;
    customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;
}

Compiling the Code

This example requires:

  • A DataGridView control named customersDataGridView that is bound to a table with the indicated column names, such as the Customers table in the Northwind sample database.

  • References to the System, System.Windows.Forms, System.Data, and System.Xml assemblies.

See Also

Tasks

How to: Bind Data to the Windows Forms DataGridView Control

Reference

DataGridView
DataGridViewColumn
System.Windows.Forms.DataGridViewColumn.DisplayIndex
System.Windows.Forms.DataGridViewColumn.Visible

Other Resources

Displaying Data in the Windows Forms DataGridView Control