2

I have a gridview control that uses templatefield CYQ2. I have formatted the field as currency in html using Text = '<%# Bind("CYQ2","{0:$#,##0.00}") %>' and it displays the field in the currency format. When I update values in the app and hit the save button, I get an error that says "input string was not in a correct format" at the line that is bold and italicized below.

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

In the IsRowModified event(code behind file), am using

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

I tried several other techniques such as NumberStyles.AllowCurrencySymbol and CultureInfo.CurrentCulture in the code behind file but nothing worked.

The point to note here is that if I use the following in the HTML markup(without dollar symbol), it works without nay issue but I need to display the dollar symbol. Text = '<%# Bind("CYQ2","{0:#,##0.00}") %>'

Can anyone please help? thanks for the help.

Additional Information(complete HTML markup of the templatefield):

<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>
4

1 回答 1

2

The problem is that the data source control you're using has simplistic parsing logic that chokes on dollar signs. Fortunately, the GridView.RowUpdating event gives you a chance to manipulate row values before they're sent on to the data source control.

In your .aspx, add an OnRowUpdating="GridView1_RowUpdating" attribute to your GridView, and handle the event like so:

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);
}
于 2013-08-07T02:29:51.990 回答