DataTable column reorder(DataTable 列重新排序)
问题描述
我正在使用带有内容的 DataTable
I'm using a DataTable with the contents
column1 column2 column3 column4 column5 column6 column7 column8 column9 column10
row1 a b c d e f g h i j
我希望将表格重新排序为
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.
推荐答案
由于您没有显示完整的代码,因此很难说到底出了什么问题.但这应该可行:
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);
}
}
你也可以使用 List<DataColumn> 或其他你喜欢的东西来代替 params String[].
Instead of a params String[] you could also use a List<DataColumn> 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");
已经在 .NET 2 中工作了.
Works already with .NET 2.
这篇关于DataTable 列重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:DataTable 列重新排序
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
