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));
}