简体   繁体   中英

C# Questions Concerning DataGridView-sorting

I have two questions:

  1. Is there a way to sort the DataGridView by column - I want to do this using code so that one of my methods can sort the DataGridView . (Same effect as if the user clicks on the column header, but without the clicking.)

  2. When I sort a column with decimal values (of type double ) the sorting believes that 9.99 is larger than 24.99 - is there any way to prevent this type of sorting behaviour?

Update: Question number 1 was solved thanks to a link in the comments. I also found the cause of the issue to question number 2: The values in my column are (double)price + "€" . I tried removing the + "€" and it started sorting the way I want. Now I want it to be able to sort, while keeping the € somehow.

Since the first question was correctly covered by stuartd, we'll focus on the second:

When I sort a column with decimal values (of type double ) the sorting believes that 9.99 is larger than 24.99 - is there any way to prevent this type of sorting behaviour?

As you've noticed, removing + "€" corrected your issue because with it that column is performing a string comparison instead of the intended double comparison. You can fix this by using a CultureInfo to format the column as a currency column instead.

CultureInfo ci = new CultureInfo("fr-FR");
this.dataGridView1.Columns[0].DefaultCellStyle.FormatProvider = ci.NumberFormat;
this.dataGridView1.Columns[0].DefaultCellStyle.Format = "c";

未排序清单 升序排序 排序

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM