DataTable column reorder

后端 未结 2 787
予麋鹿
予麋鹿 2020-12-18 02:10

I\'m using a DataTable with the contents

       column1    column2   column3  column4 column5 column6 column7 column8 column9 column10
row1   a         


        
2条回答
  •  盖世英雄少女心
    2020-12-18 02:25

    Since you haven't shown the full code it's difficult to say what's actually wrong. But this should work:

    public static void ReorderTable(ref DataTable table, params String[] columns)
    {
        if (columns.Length != table.Columns.Count)
            throw new ArgumentException("Count of columns must be equal to table.Column.Count", "columns");
    
        for (int i = 0; i < columns.Length; i++)
        {
            table.Columns[columns[i]].SetOrdinal(i);
        }
    }
    

    Instead of a params String[] you could also use a List or whatelse you prefer.

    Tested with your sample data:

    var table = new DataTable();
    table.Columns.Add("column1", typeof(string));
    table.Columns.Add("column2", typeof(string));
    table.Columns.Add("column3", typeof(string));
    table.Columns.Add("column4", typeof(string));
    table.Columns.Add("column5", typeof(string));
    table.Columns.Add("column6", typeof(string));
    table.Columns.Add("column7", typeof(string));
    table.Columns.Add("column8", typeof(string));
    table.Columns.Add("column9", typeof(string));
    table.Columns.Add("column10", typeof(string));
    
    for (int i = 0; i < 10; i++)
    {
        table.Rows.Add("colum1", "column2", "colum3", "column4", "column5", "column6", "column7", "column8", "column9", "column10");
    }
    
    ReorderTable(ref table, "column4", "column2", "column1", "column7", "column6", "column9", "column10", "column5", "column8", "column3");
    

    Works already with .NET 2.

提交回复
热议问题