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 B
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
{
///
/// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
///
///
///
/// http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order
public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
{
List 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));
}
}