【发布时间】:2012-09-18 08:14:49
【问题描述】:
我尝试使用以下两种方式对数据表进行排序
table.DefaultView.Sort = "Town ASC, Cutomer ASC"
table.Select("", "Town ASC, Cutomer ASC")
但没有一个是无效的。它始终以原始顺序显示数据。你有什么想法解决这个问题吗?
【问题讨论】:
我尝试使用以下两种方式对数据表进行排序
table.DefaultView.Sort = "Town ASC, Cutomer ASC"
table.Select("", "Town ASC, Cutomer ASC")
但没有一个是无效的。它始终以原始顺序显示数据。你有什么想法解决这个问题吗?
【问题讨论】:
这是我能找到的对 DataTable 进行排序而无需创建任何新变量的最短方法。
DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable
地点:
ASC - 上升
DESC - 降序
ColumnName - 要排序的列
DataTable - 要排序的表
【讨论】:
试试这个:
Dim dataView As New DataView(table)
dataView.Sort = " AutoID DESC, Name DESC"
Dim dataTable AS DataTable = dataView.ToTable()
【讨论】:
在 DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC") 上设置排序表达式后,您应该使用 DefaultView 而不是 DataTable 实例本身循环遍历表
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
改为使用 DataTable 的 Select 方法,生成一个 DataRow 数组。该数组是根据您的请求排序的,而不是 DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
【讨论】:
这对我有用:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();
【讨论】:
private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;
DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}
//clear the incoming dt
dt.Rows.Clear();
for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}
DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}
【讨论】: