Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change DataTable columns order

Tags:

c#

datatable

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

like image 874
Vyasdev Meledath Avatar asked Sep 21 '10 07:09

Vyasdev Meledath


People also ask

How do I rearrange columns in DataTable?

ColReorder adds the ability for the end user to be able to reorder columns in a DataTable through a click and drag operation. This can be useful when presenting data in a table, letting the user move columns that they wish to compare next to each other for easier comparison.

How do I sort a specific column in a DataTable?

The existing answers are using legacy DataTables syntax. Versions 1.10+ should use the following syntax: $('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending });

What is SetOrdinal in C#?

Changes the ordinal or position of the DataColumn to the specified ordinal or position. public: void SetOrdinal(int ordinal); C# Copy.


1 Answers

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"}); 
like image 113
default locale Avatar answered Sep 18 '22 07:09

default locale