Moving a DataTable Column

I am using DataTable with content

  column1 column2 column3 column4 column5 column6 column7 column8 column9 column10 row1 abcdefghij 

I want the table to be reordered as

  column4 column2 column1 column7 column6 column9 column10 column5 column8 column3 row1 dbagfijehc 

I tried using the DataTable.Column[i].SetOrdinal() method, but it correctly replaces only the first column.

+6
source share
2 answers

Since you have not shown the full code, it is hard to say what is actually wrong. But this should work:

 public static void ReorderTable(ref DataTable table, params String[] columns) { if (columns.Length != table.Columns.Count) throw new ArgumentException("Count of columns must be equal to table.Column.Count", "columns"); for (int i = 0; i < columns.Length; i++) { table.Columns[columns[i]].SetOrdinal(i); } } 

Instead of params String[] you can also use List<DataColumn> or whatever you prefer.

Tested by your data:

 var table = new DataTable(); table.Columns.Add("column1", typeof(string)); table.Columns.Add("column2", typeof(string)); table.Columns.Add("column3", typeof(string)); table.Columns.Add("column4", typeof(string)); table.Columns.Add("column5", typeof(string)); table.Columns.Add("column6", typeof(string)); table.Columns.Add("column7", typeof(string)); table.Columns.Add("column8", typeof(string)); table.Columns.Add("column9", typeof(string)); table.Columns.Add("column10", typeof(string)); for (int i = 0; i < 10; i++) { table.Rows.Add("colum1", "column2", "colum3", "column4", "column5", "column6", "column7", "column8", "column9", "column10"); } ReorderTable(ref table, "column4", "column2", "column1", "column7", "column6", "column9", "column10", "column5", "column8", "column3"); 

Works already with .NET 2.

+9
source
 int cnt = 0; foreach (string s in colsList) { if (table.Columns.Contains(s)) { table.Columns[s].SetOrdinal(cnt); cnt++; } } 

count does not have to be the same.

0
source

Source: https://habr.com/ru/post/927953/


All Articles