2017-03-02 103 views
0

我有一個WinForms應用程序與DataGridView列在運行時填充價格,價格是字符串數據類型。排序C#.net DataGridView列爲十進制

當我使用此列進行排序:

dgvDealerPrices.Sort(colPrice, ListSortDirection.Ascending); 

它排序價格像這樣:

£10350
£11294
£8999
£9050
£9,099
£ 9,099
£9,149
£9199
£9,199.99
£9200
£9,299
£9,457.31
£9899
£9994

很明顯,因爲它是字符串進行排序。我怎樣才能正確排序價格?即小數點,但保持顯示的字符串格式化。我曾與SortCompare屬性玩過,但無法使它工作。

+1

的可能的複製[如何排序字符串中的WinForms在datagridview的數量(http://stackoverflow.com/questions/2674670/how-to-sort -string-as-number-in-datagridview-in-winforms) – Reniuz

+0

你用一個按鈕來排序嗎? – Berkay

+0

@Berkay在DataGridView填充後以編程方式編輯 –

回答

2

您可以使用自己的比較器:

dgvDealerPrices.Sort(new PriceComparer()); 

class PriceComparer : IComparer 
{ 
    public int Compare(object x, object y) 
    { 
     var rowX = (DataGridViewRow)x; 
     var rowY = (DataGridViewRow)y; 
     var strX = (string)rowX.Cells["colPrice"].Value; 
     var strY = (string)rowY.Cells["colPrice"].Value; 
     return Decimal.Compare(Decimal.Parse(strX.Replace("£", "")), Decimal.Parse(strY.Replace("£", ""))); 
    } 
} 
+0

您的傳奇!調整它有點,它的作品一種享受! –

+1

我很高興我幫助@TomCarroll :) – MKoperski