2017-06-04 164 views
0

好吧,我有一個ListBox顯示產品(他們是一個自定義的類,並有ID,名稱,價格),在綁定列表中..我希望ListBox顯示項目名稱和價格。列表框(lbProductsChosen)將「DataTextField」設置爲名稱並將DataValueField設置爲該ID。我正在使用PreRender事件來檢查每個項目,從綁定列表(blProducts)中查看它的價格等等,它的工作效果很好。我用這個名字和價格顯示在列表中。但是,當它顯示時,儘管我使用String.Format格式化,結果仍然是一個十進制數(例如3.20000),它看起來很醜。有誰知道爲什麼它的工作顯示它,但沒有顯示它,我想如何格式化。ASP.net ListBox貨幣格式化

protected void lbProductsChosen_PreRender(object sender, EventArgs e) 
    { 
     foreach (ListItem item in lbProductsChosen.Items) 
     { 
      string currentDescription = item.Text; 
      int convertedValue = Convert.ToInt32(item.Value); 
      for (int i = 0; i < blProducts.Count; i++) 
      { 
       if (blProducts[i].ProductID == convertedValue) 
       { 
        decimal ItemPrice = blProducts[i].Price; 
        string convertedPrice = ItemPrice.ToString(); 
        string currentPrice = String.Format("{0:c}", convertedPrice); 
        string currentDescriptionPadded = currentDescription.PadRight(30); 
        item.Text = currentDescriptionPadded + currentPrice; 
       } 
      } 
     } 
    } 

回答

0

MSDN狀態下面對String.Format方法。

通常,通過使用由CultureInfo.CurrentCulture屬性返回的當前區域性的約定,將參數列表中的對象轉換爲它們的字符串表示形式。

如果您使用貨幣格式說明符c它將使用在系統設置中定義的貨幣格式。看看control panel - >region - >additional settings - >currency。也許你已經搞亂了設置。

enter image description here


如果你想忽略本地設置這將使意義的貨幣,你可以做到以下幾點。 (例如,在美元與百達小數點後兩位)

decimal price = 12.10999999m; 
String.Format("${0:0.00}", price); 

$ 12.10條

注意String.Format不正確四捨五入的數量只是砍下。

+0

謝謝。本地設置是正確的,因爲我在我的程序的其他部分使用貨幣轉換,它的工作原理。只是不知道爲什麼它不在這裏格式化,沒有錯誤。我會用你的例子嘗試一下,希望它可以工作,儘管它可能不會像我使用的格式那樣註冊它,因爲它實際上不是從本地設置。明天會提供反饋。 – Sick