c# DataView和DataGridView排序



我有一个小问题。我需要按降序对DataGridView(WinForms应用程序)中的数据进行排序。我将数据视图作为数据源应用于 myGrid:

DataView view = myDataTable.DefaultView;
view.Sort = "id DESC";
myGrid.DataSource = view;

ID 列是字符串数据类型,格式为 ##/yy。第一部分是递增整数,第二部分(在"/"之后)是当前年份的最后两位数字。不幸的是,它必须采用这种格式。

排序后,它按以下顺序返回:

9/14,8/14,7/14,6/14,5/14,4/14,3/14,2/14,10/14,1/14...

但它应该是这样的:

10/14,9/14,8/14,7/14,6/14,...

解决这个问题的最简单方法是什么?谢谢。

编辑:添加了更多信息...

这里有几个选择。您可以克隆表并通过直接修改值来修改类型和正确类型转换,也可以使用帮助器列等。这可以通过多种方式实现。我将为您提供一个简单的示例,该示例使用单个帮助程序列将字符串处理为日期,然后以这种方式排序。

如果你有一些整数(我将使用一个 16 位整数作为类型)和一个用 /分隔的两位数年份,我们可以这样写它:

// Setup a sample table to match yours
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add("id", typeof(string));
// Add some values to the table
myDataTable.Rows.Add("7/14");
myDataTable.Rows.Add("4/14");
myDataTable.Rows.Add("8/14");
myDataTable.Rows.Add("3/14");
myDataTable.Rows.Add("6/14");
myDataTable.Rows.Add("10/14");
myDataTable.Rows.Add("5/14");
myDataTable.Rows.Add("2/14");
myDataTable.Rows.Add("9/14");
myDataTable.Rows.Add("1/14");
// Add a helper column with 16-bit format based on the values in id
myDataTable.Columns.Add("helper", typeof(Int16));
// Convert the value in the id column of each row to a string,
// then split this string at the '/' and get the first value.
// Convert this new value to a 16-bit integer,
// then save it in the helper column.
foreach (DataRow row in myDataTable.Rows) row["helper"] =
    Convert.ToInt16(row["id"].ToString().Split('/')[0]);
// Create a view to match yours, sorting by helper column instead of id
DataView view = myDataTable.DefaultView;
view.Sort = "helper DESC";
//myGrid.DataSource = view;
// Write the output from this view
foreach (DataRow row in view.ToTable().Rows) Console.WriteLine(row["id"]);

产生输出...

10/14
9/14
8/14
7/14
6/14
5/14
4/14
3/14
2/14
1/14

如果还需要按年份排序,则可以以相同的方式添加其他帮助程序列。

最新更新