由於您沒有顯示完整的代碼,因此很難說出實際的錯誤。但是,這應該工作:
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);
}
}
取而代之的是params String[]
你也可以使用一個List<DataColumn>
或whatelse你喜歡。
測試你的樣本數據:
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");
廠已經與.NET 2
爲什麼要在數據表中重新排序? – Shyju
如果這是爲了在某處顯示錶格,那麼您可能會發現大多數(全部)標準顯示方式將允許您設置列顯示的順序... – Chris
可能的重複[如何更改DataTable colums爲了](http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order) –