Note that there are some explanatory texts on larger screens.

plurals
  1. PODecimal.TryParse is failing on TextBox.Leave and TextBox.LostFocus
    text
    copied!<p>This has got to be one of the most frustratingly stupid bugs I have ever encountered, and I just want to see if anybody else has run into this before. </p> <p>Here's the deal. I have a TextBox in a Windows Forms application in VB 2008 (.NET 3.5) where a user can key an estimate amount. I am allowing them to key dollars and cents, and I want to round to the nearest dollar. The original code had the rounding down when the data was written back to a table, and that worked fine - I have this code in a "Save" routine that fires when the user moves to a different screen or record:</p> <pre><code> Dim est As Decimal : Decimal.TryParse(txtEstimateAmount.Text.Trim, est) Dim estimatedAmount As Integer = Math.Round(est) </code></pre> <p>I decided that it might be nice to actually do the rounding as soon as they leave the field instead, so they're not surprised when they reload the screen and find that 1822.60 is now 1823. So I took the exact same code and added it to the TextBox.Leave event handler. And the weirdest thing happened: instead of the variable <strong>est</strong> being populated with 1822.60 after the parse, it gets set to -1! What the...? </p> <p>Debugging the handler shows that the value goes into the parser correctly, and if I do the parsing manually via the Immediate window, it parses correctly, but when I let the code do it, it invariably gets set to -1. What's even weirder is that <strong>any</strong> number gets parsed as -1, not just decimals, and any non-number gets parsed as 0 (which is correct).</p> <p>Has anybody else ever run into this before? I tried moving the code to the TextBox.LostFocus event instead, but with the same results. I have no idea what in the heck is going on, and obviously there are workarounds galore for this, but it just makes no sense whatsoever. </p> <p>EDIT: Here's the full event handler (current behavior for which is to put -1 in the TextBox):</p> <pre><code>Private Sub txtEstimateAmount_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEstimateAmount.Leave ' Take any dollars-and-cents amount and round to the nearest dollar Dim est As Decimal est = Decimal.TryParse(txtEstimateAmount.Text.Trim, est) txtEstimateAmount.Text = If(est &lt;&gt; 0, Math.Round(est).ToString(), String.Empty) End Sub </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload