Click to Rate and Give Feedback

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Windows Forms Programming 
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. For more information, see How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer.

Example

Visual Basic
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
C#
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

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker