How to change DataTable columns order

前端 未结 6 940
旧时难觅i
旧时难觅i 2020-12-02 07:46

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

6条回答
  •  天命终不由人
    2020-12-02 08:20

    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));
            }
    }
    

提交回复
热议问题