DataGridView decimal not sorting

2019-08-08 17:44发布

问题:

Alright, I have a DataGridView which is being databound like:

dataGridViewChartOre.AutoGenerateColumns = false;
dataGridViewChartOre.DataSource = xml.GetOreChart();
dataGridViewChartOre.DataMember = "ore";

All columns have been created manually via the UI. And the columns consists of 1 string, 10 decimals. Where the last column is a currency.

Now getting a currency to show in the dataGridView was quick to solve once, I remembered that the input from xml was always a string. Using this approach: (Found else where on this sites.)

private void dataGridViewChartOre_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        string value = e.Value.ToString();
        decimal d;

        if (decimal.TryParse(value, out d))
        {
            e.Value = d;
        }
    }

Now getting, the decimals to sort, seems to of a much bigger problem. I've tried a couple of suggested solutions, however none have worked so far.

  • Using float instead of decimals.
  • Utilizing the SortCompare // SortResult

Right now, it sorts all the decimals by its first number only, ie:

8616
8225
785995
7833
78069
773403
750268
74521
738249
714541
70972
and so on

So how to fix this, and even better if somebody could explain to me why it does this ?

Also, on a side note, how to change CurrencySymbol? I want to use a different symbol accross the whole program, however, it should retain the regular en-US datetime format.

回答1:

Your DataGridView Column type depends on the actual type of the underlying data. You can't change the type of the underlying data, what you changed in the CellFormatting event handler is just the cell value. If the cell value type is changed so that its type is not matched with the type of the owning column (which is determined by the underlying data), there will be a FormatException thrown. I guess your code (in CellFormatting event handler) will throw that exception if you add e.FormattingApplied = true; after changing the cell value, that will actually affect the formating but you missed it).

You mentioned SortCompare event and said it didn't help, but I think you might not use it in a correct way. I've tried this solution with it and it worked:

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
   e.SortResult = Compare(e.CellValue1.ToString(), e.CellValue2.ToString());
}
private int Compare(string a, string b)
{
   return decimal.Parse(a).CompareTo(decimal.Parse(b));
}