108

How to change Datatable columns order in c#.

Example:

am created sql table type order is Qty,Unit,Id but in program DataTable order is Id,Qty,Unit. In code Behind am directly pass DataTable to sql table type so the table order is different.

DataTable columns are: `Id,Qty,Unit.`  I want this to be: `Qty,Unit,Id` 

Please help

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Vyasdev Meledath
  • 8,926
  • 20
  • 48
  • 68
  • 1
    can you explain why you would want to change the column order? – KBoek Sep 21 '10 at 07:12
  • am created sql table type order is `Qty,Unit,Id` but in program DataTable order is `Id,Qty,Unit`. In code Behind am directly pass DataTable to sql table type so the table order is different.Thats why am asked "how to change the column order?" – Vyasdev Meledath Sep 21 '10 at 07:20
  • 7
    Just answer the OP already. – Christian Mar 24 '15 at 13:31

7 Answers7

282

Try to use the DataColumn.SetOrdinal method. For example:

dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1); 

UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:

Extension method:

public static class DataTableExtensions
{
    public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
    {
        int columnIndex = 0;
        foreach(var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

Usage:

table.SetColumnsOrder("Qty", "Unit", "Id");

or

table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});
default locale
  • 13,035
  • 13
  • 56
  • 62
8

This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.

public static class DataTableExtensions
{
    /// <summary>
    /// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
    /// </summary>
    /// <param name="table"></param>
    /// <param name="columnNames"></param>
    /// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
    public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
    {
        List<string> listColNames = columnNames.ToList();

        //Remove invalid column names.
        foreach (string colName in columnNames)
        {
            if (!dtbl.Columns.Contains(colName))
            {
                listColNames.Remove(colName);
            }
        }

        foreach (string colName in listColNames)
        {
            dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
        }
}
Soenhay
  • 3,958
  • 5
  • 34
  • 60
2

I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.

da Bich
  • 494
  • 1
  • 4
  • 13
1

If you have more than 2-3 columns, SetOrdinal is not the way to go. A DataView's ToTable method accepts a parameter array of column names. Order your columns there:

DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");
0

We Can use this method for changing the column index but should be applied to all the columns if there are more than two number of columns otherwise it will show all the Improper values from data table....................

santosh
  • 9
  • 1
0

Change DataTable Column Order

Input: DataTable Column Order

Columns

  1. COLUMN1
  2. COLUMN2
  3. COLUMN3

You need to Pass DataTable to below method and set the order according to your wish

private void ProcessDataTable(DataTable dt)
{
        //Setting Column Orders
        dt.Columns["COLUMN3"].SetOrdinal(0);
        dt.Columns["COLUMN2"].SetOrdinal(1);
        dt.Columns["COLUMN1"].SetOrdinal(2);
}

Output: DataTable Column Order

Columns

  1. COLUMN3
  2. COLUMN2
  3. COLUMN1
-6

Re-Ordering data Table based on some condition or check box checked. PFB :-

 var tableResult= $('#exampleTable').DataTable();

    var $tr = $(this).closest('tr');
    if ($("#chkBoxId").prop("checked")) 
                    {
                        // re-draw table shorting based on condition
                        tableResult.row($tr).invalidate().order([colindx, 'asc']).draw();
                    }
                    else {
                        tableResult.row($tr).invalidate().order([colindx, "asc"]).draw();
                    }
satya prakash
  • 87
  • 1
  • 5
  • Please read question carefully. Above query is for c# not for jquery – Ahmad Mukhtar Dec 24 '19 at 07:55
  • 2
    Not only is this answer for the wrong language, the question was for ordering columns not sorting rows. How did you arrive at this answer, let alone over 8 years after its accepted answer? Why? – jreed121 Mar 07 '20 at 00:46