I have a small problem. I need to sort data in the DataGridView (WinForms application) in descending order. I apply a DataView as DataSource to myGrid:
DataView view = myDataTable.DefaultView;
view.Sort = "id DESC";
myGrid.DataSource = view;
id column is string data type, and is in ##/yy format. First part is incrementing integer, second part (after '/') is last two digits of current year. Unfortunately it has to be in this format.
After sortting it returns in this order:
9/14,8/14,7/14,6/14,5/14,4/14,3/14,2/14,10/14,1/14...
But it should be like this:
10/14,9/14,8/14,7/14,6/14,...
What would be the easiest way to solve this? Thank you.
EDIT: Added some more info...
You have a few options here. You can clone your table and modify the type and typecast it properly by modifying the values directly, or you can use a helper column, etc. This can be accomplished many ways. I'll give you a simple example that uses a single helper column to process the string into a date then sort in that way.
If you have some integer (I'll use a 16-bit integer as the type) and a two-digit year separated by a /
, we can write it instead as follows:
// 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"]);
which produces the output...
10/14
9/14
8/14
7/14
6/14
5/14
4/14
3/14
2/14
1/14
If you need to sort by year as well, you can add an additional helper column in the same manner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.