2014-02-25 177 views
1

我有一个小问题。我需要按照降序对DataGridView(WinForms应用程序)中的数据进行排序。我将DataView作为DataSource应用于myGrid:c#DataView&DataGridView排序

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

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

sortting后返回顺序如下:

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,... 

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

编辑: 增加了一些详细信息...

+0

ID字段的数据类型是什么? –

+0

哦......现在我知道它为什么不按正确顺序排序...因为它是一个字符串(它是以###/yy格式)。有没有办法对它进行排序,即使它是一个字符串? – user1080533

+0

可能的重复http://stackoverflow.com/questions/7572685/sort-string-items-in-a-datatable-as-int-using-c-sharp – Dmitry

回答

1

你这里有几个选项。你可以通过直接修改值来克隆你的表并修改它的类型和类型,或者你可以使用助手列等等。这可以通过许多方式来完成。我会给你一个简单的例子,它使用单个帮助者列将字符串处理成日期,然后按这种方式排序。

如果你有一些整数(我将使用一个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 

如果您还需要按年份排序,您可以以相同的方式添加一个辅助列。

+0

嗨,谢谢你的回答,不幸的是它不是yyyy/mm。第一部分('/'之前)是递增整数,第二部分('/'之后)是年份的后两位数字。它必须在这种格式不幸... – user1080533

+0

@ user1080533我已经更新了我的答案。 – grovesNL

+0

哇,谢谢。会给它一个尝试和告诉,它是如何去的 – user1080533