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. Also see How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer.

Example

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

Compiling the Code

This example requires:

See also