2013-08-06 32 views
2

我有一個使用templatefield CYQ2的gridview控件。我使用Text = '<%# Bind("CYQ2","{0:$#,##0.00}") %>'將此字段格式化爲html中的貨幣,並以貨幣格式顯示該字段。當我更新應用程序中的值並點擊保存按鈕時,出現一個錯誤,提示「輸入字符串的格式不正確」在下面粗體和斜體的行處。GridView - 輸入字符串格式不正確

protected void UpdateButton_Click(object sender, EventArgs e) 
    { 
     originalDataTable = (System.Data.DataTable)ViewState["originalValuesDataTable"]; 

     foreach (GridViewRow r in GridView1.Rows) 
      ***if (IsRowModified(r)) { GridView1.UpdateRow(r.RowIndex, false); }*** 

在IsRowModified事件(隱藏文件的代碼),現在用

currentQ2 = Decimal.Parse(((TextBox)r.FindControl("CYQ2TextBox")).Text, NumberStyles.Currency); 

我嘗試過其他幾種技術,如NumberStyles.AllowCurrencySymbol和CultureInfo.CurrentCulture在隱藏文件,但沒有代碼工作。

這裏需要注意的是,如果我在HTML標記(沒有美元符號)中使用以下內容,它的工作原理沒有問題,但我需要顯示美元符號。 Text = '<%# Bind("CYQ2","{0:#,##0.00}") %>'

任何人都可以請幫忙嗎?謝謝您的幫助。

附加信息(模板列的完整的HTML標記):

<asp:TemplateField HeaderText="Q2" SortExpression="CYQ2"> 
      <EditItemTemplate> 
       <asp:TextBox ID="CYTextBox" runat="server" Text='<%# Bind("CYQ2") %>' Width="40"></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:TextBox ID="CYQ2TextBox" runat="server" MaxLength="20" Width="40" 
       Text = '<%# Bind("CYQ2","{0:$#,##0}") %>' Font-Names="Tahoma" Font-Size="8pt"></asp:TextBox> 
      </ItemTemplate>   
       <HeaderStyle Width="40px" Font-Names="Tahoma" Font-Size="8pt"/> 
       <ItemStyle Width="40px" HorizontalAlign="Right" />  
      </asp:TemplateField> 
+0

是在'IsRowModified'調用'Decimal.Parse'發生的異常,或在調用'GridView1.UpdateRow'? –

+0

你有沒有考慮過使用ASP.NET Label控件而不是TextBox作爲'ItemTemplate',然後在其前面放置另一個標籤,它只顯示硬編碼的美元符號('$')?這將允許您顯示美元符號,而無需在您的邏輯中對其進行會計處理。如果您願意,我可以將此代碼作爲答案發布,但我不想爲不適合您情況的解決方案提供答案。 –

+1

嘗試將'Text ='<%#Bind(「CYQ2」,「{0:$#,## 0}」)%>''更改爲'Text ='<%#Bind(「CYQ2」,「{0 :C}「)%>''來輕鬆獲得貨幣格式。 – Gloria

回答

2

的問題是,你正在使用的數據源控件上的美元符號扼流圈簡單化的分析邏輯。幸運的是,GridView.RowUpdating事件讓您有機會在將數據發送到數據源控件之前處理行值。

在.aspx,添加一個OnRowUpdating="GridView1_RowUpdating"屬性您GridView,並處理像這樣的事件:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 
    string value = e.NewValues["CYQ2"].ToString(); 
    // "value" is the text entered by the user, including the dollar sign. 
    // Parse the value with the Currency style so that the data source can handle it: 
    e.NewValues["CYQ2"] = decimal.Parse(value, NumberStyles.Currency); 
} 
+0

謝謝你,它像一個魅力工作! – sam