DataGridView Columns Reordering Themselves After Build.

DESCRIPTION
This problem arises when you build and run an application that includes the DataGridView Control. Columns reorder themselves spontaneously during runtime This occurs despite having defined the order of columns using either the Column Edit dialog or Smart tag and rebuilding the project.

This problem stumped me for quite a long time. The first attempt at solving it was to try and use a binding source instead of binding directly to the DataTable.
This appeared to work momentarily but the problem reappeared after a couple of Compile/ Run cycles

This appears to be a bug intrinsic to either the designer code generator or the DataGridView control itself. See solution below.



SOLUTION:Define the order of DataGridView columns programmatically.

The ‘not so elegant’ but 100% effective solution to this problem is to define the order of the columns programmatically.
This can be done using the DisplayIndex property of the DataGridViewColumn class.

The Sample C# Code below shows how to order DataGridView Columns using code.

private void OrderGridColumns()
 {
       ProductDataGridView.Columns["ProductID"].Visible = false;
       ProductsDataGridView.Columns["ProductPrice"].DisplayIndex = 0;
       ProductsDataGridView.Columns["ProductName"].DisplayIndex = 1;
       ProductsDataGridView.Columns["Quantity"].DisplayIndex = 2;
       ProductsDataGridView.Columns["OrderDate"].DisplayIndex = 3;
 } 

The problem disappeared forever after implementing the above code in my form class and calling it from the constructor as follows

Class frmDisplayProducts
{
Public frmDisplayProducts()
 {
 InitializeComponent();
 OrderGridColumns();
 }
……… 

The above worked for me but if anyone has a more elegant solution please suggest it in the comments below.

technorati tags ,

Leave a Reply