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.
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
You should change columns order in a loop from array of column name that each column name placed in correct order in array. For more information go to this link : How to change DataTable columns order
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With