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

3
  • 1
    can you explain why you would want to change the column order?
    – KBoek
    Sep 21, 2010 at 7: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?" Sep 21, 2010 at 7:20
  • 7
    Just answer the OP already.
    – Christian
    Mar 24, 2015 at 13:31

7 Answers 7

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"});
5
  • by giving as you told,table structure changed to Qty,Id,Unit only.I want like this Qty,Unit,Id. Sep 21, 2010 at 7:36
  • Ofc, you should use this method for all of the columns except the last. Sep 21, 2010 at 8:02
  • 6
    better method body: var colIndex = 0; foreach (var colName in columnNames) table.Columns[colName].SetOrdinal(colIndex++);
    – JoelFan
    Sep 17, 2015 at 23:16
  • 1
    @JoelFan I've updated my answer, thank you! Your code definitely looks cleaner. Sep 22, 2015 at 14:02
  • 2
    very helpful, tnx. Dec 13, 2016 at 13:56
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));
        }
}
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.

2

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....................

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();
                    }
2
  • Please read question carefully. Above query is for c# not for jquery Dec 24, 2019 at 7: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 7, 2020 at 0:46

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.