Export (0) Print
Expand All

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

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

Community Additions

ADD
Show:
© 2014 Microsoft