数据表列重新排序 [英] DataTable column reorder
本文介绍了数据表列重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了一个数据表
的内容
column1 column2 column3 column4 column5 column6 column7 column8 column9 column10
row1 a b c d e f g h i j
我想桌边reorderd为
I want the table to be reorderd as
column4 column2 column1 column7 column6 column9 column10 column5 column8 column3
row1 d b a g f i j e h c
我尝试使用 DataTable.Column [I] .SetOrdinal()
方法,但它只是交换第一列正常。
I tried using the DataTable.Column[i].SetOrdinal()
method but it swaps only the first column properly.
推荐答案
既然你还没有表现出完整的code这是很难说什么是其实是错误的。但是,这应该工作:
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);
}
}
或 whatelse你$ P;
而不是一个 PARAMS的String []
你也可以使用名单,其中的;的DataColumn&GT $ PFER。
Instead of a params String[]
you could also use a List<DataColumn>
or whatelse you prefer.
测试你的样本数据:
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已经工作。
Works already with .NET 2.
这篇关于数据表列重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文