8

I'm using a DataTable with the contents

       column1    column2   column3  column4 column5 column6 column7 column8 column9 column10
row1   a           b         c         d       e       f       g      h       i        j

I want the table to be reorderd as

        column4    column2    column1  column7 column6 column9 column10 column5 column8 column3
row1     d         b           a         g      f       i       j        e       h       c    

I tried using the DataTable.Column[i].SetOrdinal() method but it swaps only the first column properly.

dandan78
  • 13,328
  • 13
  • 64
  • 78
Dwellerincellar
  • 145
  • 1
  • 2
  • 12
  • 2
    why do you want to reorder in the datatable ? – Shyju Oct 17 '12 at 15:22
  • if this is for displaying the table somewhere then you will probably find that most (all) of the standard ways of showing it will allow you to set what order the columns show in... – Chris Oct 17 '12 at 15:27
  • possible duplicate of [How to change DataTable colums order](http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order) – default locale Feb 21 '14 at 12:33

2 Answers2

12

Since you haven't shown the full code it's difficult to say what's 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 a params String[] you could also use a List<DataColumn> or whatelse you prefer.

Tested with your sample 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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1
int cnt = 0;
foreach (string s in colsList)
{
    if (table.Columns.Contains(s))
    {
        table.Columns[s].SetOrdinal(cnt);
        cnt++;
    }
}

count need not to be the same.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Rama Krishna
  • 645
  • 10
  • 28