2012-06-03 53 views
1

以下代碼是我的gridview的rowdatabound事件。它適用於除單元格文本格式之外的其他所有內容。實際上,我在格式化貨幣 的代碼行導致代碼出錯。如果我將FormatCurrency行註釋掉,代碼工作正常。爲什麼這一行a)。不格式化單元格的文本和b)。導致錯誤?在rowdatabound上格式化gridview單元格文本

Protected Sub gvDataRetrieval_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvDataRetrieval.RowDataBound 
    If e.Row.RowType = DataControlRowType.DataRow Then 
     Dim dateindex As Integer = GetColumnIndexByHeaderText(gvDataRetrieval, "date") 
     e.Row.Cells(dateindex).Text = Split(e.Row.Cells(dateindex).Text, " ")(0) 
     For i As Integer = 0 To e.Row.Cells.Count - 1 
      e.Row.Cells(i).Font.Size = 10 
      e.Row.Cells(i).HorizontalAlign = HorizontalAlign.Center 
      If i > dateindex Then 
       If Convert.ToDecimal(e.Row.Cells(i).Text) < 0 Then 
        e.Row.Cells(i).ForeColor = Drawing.Color.Red 
       Else 
        e.Row.Cells(i).ForeColor = Drawing.Color.Black 
       End If 
      End If 
      e.Row.Cells(i).Text = FormatCurrency(e.Row.Cells(i).Text, 0) 
     Next 
    End If 

End Sub 
+0

什麼是錯誤? – codingbiz

+0

輸入字符串的格式不正確,但似乎並非如此 – dinotom

回答

2

至於別人上面說的,你的代碼會報錯,如果你試圖格式化非數字值作爲貨幣,在我看來你並沒有這樣做。

相反,如果你想要一個特定的列被格式化爲貨幣,使用列的DataFormatString屬性爲這樣:

<asp:BoundColumn DataField="YourCurrencyField" DataFormatString="{0:C}" /> 

很顯然,你還需要確保你的領域是一個有效的可以格式化爲貨幣的數字。

+0

網格是動態的,我該如何設置這個專業版perty在代碼背後?這會工作嗎?我已經嘗試將單元格文本轉換爲十進制和雙精度,並且格式和前面的顏色變化不一致。 – dinotom

+0

通過動態,您是指您在後面的代碼中創建列或者僅僅是自動生成列?無論哪種方式,您也可以通過編程設置DataFormatString屬性。 – Icarus

0

移動

e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString() 

到如果函數。該行不檢查是否是日期欄。可能正試圖尋找一個日期轉換爲貨幣

 If i > dateindex Then 
      If Convert.ToDecimal(e.Row.Cells(i).Text) < 0 Then 
       e.Row.Cells(i).ForeColor = Drawing.Color.Red 
      Else 
       e.Row.Cells(i).ForeColor = Drawing.Color.Black 
      End If 
      e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString() 
     End If 
+0

是的,我在那裏試過。雖然現在瀏覽器上顯示的錯誤突出顯示了「If Convert.ToDecimal .... code line。If if I> dateindex sequence」,但單元格文本將格式化爲貨幣,但不會執行forecolor更改和貨幣格式...爲什麼?此外,這行定義爲貨幣格式化程序..... e.Row.Cells(1).Text = FormatCurrency(e.Row.Cells(1).Text,0 ) – dinotom

+0

有可能一旦我將單元格的文本格式化爲貨幣時,Convert.ToDecimal不再有效嗎? – dinotom

+0

單步執行代碼並查看檢查變量值,例如dateindex,e.Row.Cells(i).Text - there可能是一些無效的數值後dateindex網格列 – codingbiz

3

嘗試使用

而不是

e.Row.Cells(i).Text = Format(e.Row.Cells(i).Text, "c0").ToString() 
+0

不好,這個問題似乎在於,事實上,編譯器不喜歡forecolor更改和字符串格式在一起...至少不是我怎麼一直試圖做 – dinotom

0

我在C#中遇到了同樣的問題,並通過將文本轉換爲double來解決,然後將double格式化爲字符串。

我知道這是VB而不是C#,但我想我會分享我的解決方案,因爲它出現在我的Google結果中,並可能幫助某人。

double d; 
Double.TryParse(r.Cells[i].Text, out d); 
e.Cells[i].Text = String.Format("{0:C0}", d).ToString();