Home > front end >  I got an error on calculations with textbox vb.net
I got an error on calculations with textbox vb.net

Time:04-27

I try to do some calculation with textbox but i get error on the results the right result is 3700 = 4000 -300 but i get 3667 instead of 3700 i use this code

Private Sub Txtpaid_TextChanged(sender As Object, e As EventArgs) Handles Txtpaid.TextChanged
        Dim totalcredit As Decimal
        totalcredit = Val(Txtforhim.Text) - Val(Txtpaid.Text)
        Txtforhim.Text = totalcredit.ToString
    End Sub

CodePudding user response:

Add a breakpoint to the function, so you can see exactly what the code is doing during that method. Alternatively, you can add a MsgBox() like this:

Private Sub Txtpaid_TextChanged(sender As Object, e As EventArgs) Handles Txtpaid.TextChanged
    MsgBox($"Forhim Text: {Txtforhim.Text}{vbCrLf}Forhim Value: {Val(Txtforhim.Text)}{vbCrLf}Paid Text: {Txtpaid.Text}{vbCrLf}Paid Value: {Val(Txtpaid.Text)}")

    Txtforhim.Text = (Val(Txtforhim.Text) - Val(Txtpaid.Text)).ToString()
End Sub

I also strongly recommend using Decimal.Parse() or Decimal.TryParse() instead of Val(), which can be kind of naiive.

CodePudding user response:

The code is converting the text in the TextBox controls and then finding the difference.

There are some very bad design flaws here. For one, you should be using a NumericUpDown control (aka NUD) as opposed to a TextBox. NUDs provide users a way to only enter numeric values. NUDs also have a Value property (documentation) which returns a Decimal.

You are also using the legacy Visual Basic holdover, Val. Val works by trying to convert a String but stops reading the String at the first character that it can't recognize as part of a number. So if you use a comma for a decimal point and use Val("1,23") then the result of this operation is 1 because the first character that it didn't recognize as part of a number was the comma. If you wanted to continue using TextBox controls, then you should use Decimal.TryParse (documentation).

  • Related