c#如何更改 DataTable 列的顺序

dataTable.Columns["Qty"].SetOrdinal(0); 
dataTable.Columns["Unit"].SetOrdinal(1);  

扩展方法:

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

用法:

table.SetColumnsOrder("Qty", "Unit", "Id"); 

table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"}); 

 

posted @ 2023-11-11 22:22  James·wang  阅读(771)  评论(0编辑  收藏  举报