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
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.
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 });
Changes the ordinal or position of the DataColumn to the specified ordinal or position. public: void SetOrdinal(int ordinal); C# Copy.
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"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With