Reorder dataTable columns

c#, winforms

Solution

This process seems easy but not really such easy. The point is whenever you change the `Ordinal` of a column from `x` to a lower ordinal `a` (a < x) then all the columns with ordinals between `a` and `x` will be shifted right, if `x` is changed to a higher ordinal `b` (b > x) then all the columns with ordinals between `x` and `b` wil be shifted left. We must perform some update each time a column's ordinal is changed.

You can prepare a list of your column `indices` in the order you want, something like this:

List<int> indices = new List<int>{1,2,0,7,4,5,3,6};

for(int i = 0; i < indices.Count; i++){
   dataTable.Columns[indices[i]].SetOrdinal(i);
   if(indices[i] > i){
      for(int j = i; j < indices.Count; j++)
         if(indices[j] >= i && indices[j] < indices[i]) indices[j]++;//Right shifted                       
   }
   else if(indices[i] < i){
      for(int j = i; j < indices.Count; j++)
         if(indices[j] >= indices[i] && indices[j] < i) indices[j]--;//Left shifted
   }
}    

Or you can also prepare a list of your `ColumnName` in the order you want, something like this:

List<string> columns = new List<string>{"Column2","Column1","Column5","Column3","Column6","Column4"};
//The same code as above

Problem

I'm reordering my dataTable columns using : ``` dataTable.Columns[int x].SetOrdinal(int y) ``` However, I use it for each column and that doesn't to work for me. For instance : ``` dataTable.Columns[0].SetOrdinal(1); dataTable.Columns[1].SetOrdinal(0); ``` Makes a double inversion... And in my code, I have to define where each column must be. Is there any solution to this ? Thank you.

Original source

Related problems