locked
Input string was not in a correct format. RRS feed

  • Question

  • User2028823583 posted

    I have a Decimal that I'm using to calculate some subTotals and Totals from row's in a grid view.  This code below all works great UNTIL I run into a negative number in the grid.  Is it possible to convert a Negative Value to a Decimal so I can keep a running sub total? 

    The error I'm getting is Input string was not in a correct format. 

    Dim requestedSubTotal As Decimal = 0.0
    
    For Each row As GridViewRow In gvReport.Rows
      Dim lblAmountRequestedSubTotal As Label = DirectCast(row.FindControl("lblAmountRequested"), Label)
    
    requestedSubTotal += Convert.ToDecimal(Replace(lblAmountRequestedSubTotal.Text, "$", ""))
    
    Next
    
    
    



    Wednesday, September 12, 2018 5:22 PM

Answers

  • User475983607 posted

    IMHO, it is much easier to do math on an actual typed result set rather than writing a bunch of code to parse strings. 

    With that being said, use Decimal.Parse() or Decimal.TryParse().

    Dim value As Decimal
    value = Decimal.Parse("-$3.1415", System.Globalization.NumberStyles.AllowDecimalPoint Or System.Globalization.NumberStyles.AllowLeadingSign Or System.Globalization.NumberStyles.Currency)
    Dim result As Decimal = 0.00
    Decimal.TryParse("-3.1415", result)
    Console.WriteLine(result)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 12, 2018 5:39 PM

All replies

  • User475983607 posted

    IMHO, it is much easier to do math on an actual typed result set rather than writing a bunch of code to parse strings. 

    With that being said, use Decimal.Parse() or Decimal.TryParse().

    Dim value As Decimal
    value = Decimal.Parse("-$3.1415", System.Globalization.NumberStyles.AllowDecimalPoint Or System.Globalization.NumberStyles.AllowLeadingSign Or System.Globalization.NumberStyles.Currency)
    Dim result As Decimal = 0.00
    Decimal.TryParse("-3.1415", result)
    Console.WriteLine(result)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 12, 2018 5:39 PM
  • User1359968896 posted

    Check http://msdn.microsoft.com/en-us/library/sf1aw27b.aspxfor exceptions.

    <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="6" data-gr-id="6">Use</g><g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="6" data-gr-id="6"> </g>Int32.TryParse(value, out number)<g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="6" data-gr-id="6"> </g><g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="6" data-gr-id="6">instead</g>. That will solve your problem.

    int imageWidth;
    if(Int32.TryParse(Label1.Text, out imageWidth))
    {
        Image1.Width= imageWidth;
    }
    Thursday, September 13, 2018 5:55 AM