Results 1 to 28 of 28

Thread: Help with calculate button

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Help with calculate button

    I am a recent college graduate and I hope to use this forum to keep my skills sharp.

    I am making a program to calculate depreciation (just to apply what I learned) and when I run the program and made the input, I get an error that says "Please input numeric values." Here is the code for the calculate button (If you need me to post anything else, please say so) :

    Code:
      Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
            'Declaring variables for this button.
            Dim InitialCost, Salvage, LifeInYears As Integer
            Dim DepreciableCost, YearlyDepreciation As Decimal
            Try
                'Convert input values to numeric variables.
                InitialCost = Integer.Parse(CostTextBox.Text)
                Salvage = Integer.Parse(SalvageTextBox.Text)
                LifeInYears = Integer.Parse(LifeTextBox.Text)
                DepreciableCost = Decimal.Parse(DepreciableCostTextBox.Text)
                YearlyDepreciation = Decimal.Parse(YearlyDepreciationTextBox.Text)
    
                'Calculate numeric values.
                DepreciableCost = InitialCost - Salvage
                YearlyDepreciation = DepreciableCost / LifeInYears
    
                'Display output
                If DepreciableCost <= 0 Then
                    MessageBox.Show("Depreciable cost cannot be a negative number.", "Seriously?!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Else
                    DepreciableCostTextBox.Text = DepreciableCost.ToString("N2")
                    YearlyDepreciationTextBox.Text = YearlyDepreciation.ToString("N2")
    
    
                End If
    
            Catch ex As Exception
                MessageBox.Show("Please input numeric values.", "OOPS!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try
    
        End Sub

  2. #2
    Addicted Member
    Join Date
    Apr 2008
    Posts
    193

    Re: Help with calculate button

    What exception is being thrown?
    With out seeing other bits of code, I would say that one of your values is not able to be parsed.
    ...
    If someone helps you, show it by rating their post!
    VB.net Code:
    1. ' These two lines will make your coding life much easier!
    2. Option Explicit On
    3. Option Strict On

    "Check everything. That's what software developers do." jmcilhinney

  3. #3

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    This exception is to make sure that the user inputs numbers and not non-numbers such as letters. If you require to see the form and the whole code for that form, I'll provide it now. Also this form is to calculate the Straight-Line method of depreciation: Cost - Salvage / Life.

    Code:
     Public Class StraighLineForm
    
    
    
    
        Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
            MainForm.Show()
    
        End Sub
    
        Private Sub EraseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EraseButton.Click
            CostTextBox.Clear()
            SalvageTextBox.Clear()
            LifeTextBox.Clear()
            YearlyDepreciationTextBox.Clear()
            DepreciableCostTextBox.Clear()
    
        End Sub
    
        Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
            'Declaring variables for this button.
            Dim InitialCost, Salvage, LifeInYears As Integer
            Dim DepreciableCost, YearlyDepreciation As Decimal
            Try
                'Convert input values to numeric variables.
                InitialCost = Integer.Parse(CostTextBox.Text)
                Salvage = Integer.Parse(SalvageTextBox.Text)
                LifeInYears = Integer.Parse(LifeTextBox.Text)
                DepreciableCost = Decimal.Parse(DepreciableCostTextBox.Text)
                YearlyDepreciation = Decimal.Parse(YearlyDepreciationTextBox.Text)
    
                'Calculate numeric values.
                DepreciableCost = InitialCost - Salvage
                YearlyDepreciation = DepreciableCost / LifeInYears
    
                'Display output
                If DepreciableCost <= 0 Then
                    MessageBox.Show("Depreciable cost cannot be a negative number.", "Seriously?!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Else
                    DepreciableCostTextBox.Text = DepreciableCost.ToString("N2")
                    YearlyDepreciationTextBox.Text = YearlyDepreciation.ToString("N2")
    
    
                End If
    
            Catch ex As Exception
                MessageBox.Show("Please input numeric values.", "OOPS!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try
    
        End Sub
    End Class
    Attached Images Attached Images  

  4. #4
    Addicted Member
    Join Date
    Apr 2008
    Posts
    193

    Re: Help with calculate button

    You are just catching any exception in your Try/Catch block, but you do not know what exception is being thrown therefore, you, I or anybody else is not going to be able to tell what is the source of your error.
    A quick thing to do would be to either but the ex.message in your MessageBox.Show.
    Or you could run your code outside of the Try/Catch block and use the debugger to see what line of code fails.
    ...
    If someone helps you, show it by rating their post!
    VB.net Code:
    1. ' These two lines will make your coding life much easier!
    2. Option Explicit On
    3. Option Strict On

    "Check everything. That's what software developers do." jmcilhinney

  5. #5

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    I ran the code outside the block, and a logical error occurred. I hope you can read it.
    Attached Images Attached Images  

  6. #6
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    at the beginning of your click event, do something like this

    if not isnumeric(txtCost.text) then
    msgbox ("Cost must be a number. Try again")
    exit sub

    if not isnumeric(txtSalvage.text) then
    msgbox ("Salvage must be a number. Try again")
    exit sub



    and do something for each of the input boxes you need to validate.

    you could also use the validating event to make sure the values are numeric before continuing.

    you should always validate input =)

    once you know they are numeric, you do not NEED to use the .parse methods as VB will do it for you, but thats not a bad thing to do.

  7. #7
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    also, just set a breakpoint at the

    MessageBox.Show("Please input numeric values

    line and in the immediate window, type

    ? ex.stacktrace

    to get the line number where things exploded.

    you do not need to remove the try catch block

  8. #8

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by EricPeterson87 View Post
    at the beginning of your click event, do something like this

    if not isnumeric(txtCost.text) then
    msgbox ("Cost must be a number. Try again")
    exit sub

    if not isnumeric(txtSalvage.text) then
    msgbox ("Salvage must be a number. Try again")
    exit sub

    Thanks so much for this. It worked, though you forgot to put EndIf at the end of the If statements.



    once you know they are numeric, you do not NEED to use the .parse methods as VB will do it for you, but thats not a bad thing to do.
    When I was in college, I was taught how to program with VB 2008, and using the parse method was part of what I was taught. :P

  9. #9

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by EricPeterson87 View Post
    also, just set a breakpoint at the

    MessageBox.Show("Please input numeric values

    line and in the immediate window, type

    ? ex.stacktrace

    to get the line number where things exploded.

    you do not need to remove the try catch block
    Should I put this at the end of the MessageBox.show line? BTW, though I just googled "Breakpoints VB 2010", breakpoints are new to me.

  10. #10
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    you can put it on the catch line too and just step into to get to the next line. either way.

    sorry about the end ifs. i was just giving an example. glad that worked for ya

  11. #11

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    I am embarrassed...the VB program says that my variables are not used, and I declared the input, calculations and output? Am I missing something?
    Attached Images Attached Images  

  12. #12
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    it may be because you didnt initialize them. add

    = 0

    at the end of the 2 dim lines and see if it goes away.

    you still need some error checking in there. if someone puts an 'a' in one of the boxes, BOOM. =)

  13. #13

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by EricPeterson87 View Post
    it may be because you didnt initialize them. add

    = 0

    at the end of the 2 dim lines and see if it goes away.

    you still need some error checking in there. if someone puts an 'a' in one of the boxes, BOOM. =)
    Ok this is what I did:

    Code:
      Dim InitialCost As Integer = 0
    Dim Salvage As Integer = 0
    Dim LifeInYears = 0
    Dim DepreciableCost As Decimal = 0
    By doing that the green lines vanished, but when I put

    Code:
      Dim InitialCost As Integer = 0
    Dim Salvage As Integer = 0
    Dim LifeInYears = 0
    Dim DepreciableCost As Decimal = 0
    Dim YearlyDepreciation As Decimal = 0

    The green lines returned for ALL the declared varaibles.

  14. #14
    Addicted Member
    Join Date
    Apr 2008
    Posts
    193

    Re: Help with calculate button

    Attachment 87312
    Quote Originally Posted by BlueLink View Post
    ...
    By doing that the green lines vanished, but when I put

    Code:
      Dim InitialCost As Integer = 0
    Dim Salvage As Integer = 0
    Dim LifeInYears = 0
    Dim DepreciableCost As Decimal = 0
    Dim YearlyDepreciation As Decimal = 0

    The green lines returned for ALL the declared varaibles.
    Are you sure, I just pasted your code into a project and that is not the case, maybe you have somethng else going on?
    Attached Images Attached Images  
    ...
    If someone helps you, show it by rating their post!
    VB.net Code:
    1. ' These two lines will make your coding life much easier!
    2. Option Explicit On
    3. Option Strict On

    "Check everything. That's what software developers do." jmcilhinney

  15. #15
    Member
    Join Date
    Mar 2011
    Posts
    56

    Re: Help with calculate button

    Code:
            Dim InitialCost, Salvage, LifeInYears As Integer
            Try
                'Convert input values to numeric variables.
                InitialCost = Integer.Parse(CostTextBox.Text)
                Salvage = Integer.Parse(SalvageTextBox.Text)
                LifeInYears = Integer.Parse(LifeTextBox.Text)
    
                'Display output
                If (InitialCost - Salvage) <= 0 Then
                    MessageBox.Show("Depreciable cost cannot be a negative number.", "Seriously?!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Else
                    DepreciableCostTextBox.Text = InitialCost - Salvage
                    YearlyDepreciationTextBox.Text = (InitialCost - Salvage) / LifeInYears
                End If
    
            Catch ex As Exception
                MessageBox.Show("Please input numeric values.", "OOPS!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try

  16. #16

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    I declared the variables to be calculated as global variables instead of local variables and the green lines vanished for all of them. Now the only issue left is displaying the output. The depreciable cost cannot be 0 or less.

    Code:
       'Convert input values to numeric variables.
            InitialCost = CostTextBox.Text
            Salvage = SalvageTextBox.Text
            LifeInYears = LifeTextBox.Text
            DepreciableCost = DepreciableCostTextBox.Text
            YearlyDepreciation = YearlyDepreciationTextBox.Text
    
            
    
    
            'Calculate numeric values.
            DepreciableCost = InitialCost - Salvage
            YearlyDepreciation = DepreciableCost / LifeInYears
    
    
            'Display output
            If DepreciableCost <= 0 Then
                MessageBox.Show("Depreciable cost cannot be 0 or a negative number.", "Seriously?!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                DepreciableCostTextBox.Text = DepreciableCost.ToString("N2")
                YearlyDepreciationTextBox.Text = YearlyDepreciation.ToString("N2")
    
    
            End If
    
    
    
    
        End Sub
    End Class
    And you're right, there's still some input validation to be done. When I put "a" in one of the text boxes, the debug pointed to this as "the following exception was unhandled".

    Code:
      If LifeTextBox.Text = 0 Then
                MsgBox("Life cannot be 0.  Try Again.")
            End If

  17. #17
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    at the beginning of your click event, do something like this

    if not isnumeric(txtCost.text) then
    msgbox ("Cost must be a number. Try again")
    exit sub

    if not isnumeric(txtSalvage.text) then
    msgbox ("Salvage must be a number. Try again")
    exit sub

    and the issues with entering non numbers will go away =)

  18. #18
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Help with calculate button

    to avoid bad input crashing your app, use this:

    vb Code:
    1. if integer.tryparse(CostTextBox.Text, InitialCost) then
    2.     'textbox contains an integer
    3.     'InitialCost now equals that number
    4. end if

    all of the other numeric datatypes also have a tryparse method

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Help with calculate button

    @EricPeterson87 + the OP.

    the tryparse method is .Net code.
    isNumeric works but it's legacy code so not recommended

  20. #20
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Salt Lake City
    Posts
    313

    Re: Help with calculate button

    True but it works.

  21. #21
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Help with calculate button

    Quote Originally Posted by EricPeterson87 View Post
    True but it works.
    True, but for how much longer?
    Better to learn the uptodate methods now. In the future Microsoft could remove legacy support + you'll need to learn the current methods anyway.

  22. #22
    New Member bangus's Avatar
    Join Date
    Jun 2011
    Location
    Bangus Capital of the World
    Posts
    5

    Re: Help with calculate button

    @ BlueLink, I've just deployed my Asset Mgt System last week, you may try this:

    Code:
    Dim tempPS As New Double
    Dim tempSLN As New Double
    Dim tempMonthlyExp As New Double
    
    tempPS = Convert.ToDouble(IIf(txtprice.Text = "", "0.00", txtprice.Text)) _
                                    - Convert.ToDouble(IIf(txtSalvage.Text = "", "0.00", txtSalvage.Text))
                    tempSLN = tempPS _
                                    / Convert.ToDouble(IIf(txtLife.Text = "", "0.00", txtLife.Text)) 'depreciation
                    tempMonthlyExp = tempSLN _
                                    / 12 'monthly expenses

  23. #23

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by .paul. View Post
    to avoid bad input crashing your app, use this:

    vb Code:
    1. if integer.tryparse(CostTextBox.Text, InitialCost) then
    2.     'textbox contains an integer
    3.     'InitialCost now equals that number
    4. end if

    all of the other numeric datatypes also have a tryparse method
    I'm so sorry for not replying in so long, but your response worked after taking a long time to figure it out.

    Code:
      'avoiding bad input
            If Integer.TryParse(CostTextBox.Text, InitialCost) Then
                InitialCost = Integer.Parse(CostTextBox.Text)
            End If
    
            If Integer.TryParse(SalvageTextBox.Text, Salvage) Then
                Salvage = Integer.Parse(SalvageTextBox.Text)
    
            End If
    
            If Integer.TryParse(LifeTextBox.Text, LifeInYears) Then
                LifeInYears = Integer.Parse(LifeTextBox.Text)
            End If
    
            If Integer.TryParse(DepreciableCostTextBox.Text, DepreciableCost) Then
                DepreciableCost = Decimal.Parse(DepreciableCostTextBox.Text)
            End If
    
            If Integer.TryParse(YearlyDepreciationTextBox.Text, YearlyDepreciation) Then
                YearlyDepreciation = Decimal.Parse(YearlyDepreciationTextBox.Text)
            End If
    The thing about inputting non-numeric characters means that the app will record it as 0; that's better than the app crashing though. Thanks so much for this.

  24. #24
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Help with calculate button

    you nearly got it. this:

    vb Code:
    1. 'avoiding bad input
    2. If Integer.TryParse(CostTextBox.Text, InitialCost) Then
    3.     InitialCost = Integer.Parse(CostTextBox.Text)
    4. End If

    can be written as this:

    vb Code:
    1. Integer.TryParse(CostTextBox.Text, InitialCost)

    as the 2nd parameter (InitialCost) is passed ByRef

  25. #25

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by .paul. View Post

    can be written as this:

    vb Code:
    1. Integer.TryParse(CostTextBox.Text, InitialCost)

    as the 2nd parameter (InitialCost) is passed ByRef

    When I tried to do your suggested code for the output boxes(DepreicableCostTextBox.Text and YearlyDepreciationTextBox.Text), it crashed and I got this when I ran it.
    Attached Images Attached Images  

  26. #26
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Help with calculate button

    instead of:

    vb Code:
    1. Integer.TryParse(DepreciableCostTextBox.Text, DepreciableCost)
    2. DepreciableCost = Decimal.Parse(DepreciableCostTextBox.Text)

    use this:

    vb Code:
    1. Decimal.tryParse(DepreciableCostTextBox.Text, DepreciableCost)

    also, check your datatypes. DepreciableCost should be declared as Decimal + not Integer

  27. #27

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    Quote Originally Posted by .paul. View Post
    instead of:


    also, check your datatypes. DepreciableCost should be declared as Decimal + not Integer
    LOL, that's what I get for not proofreading...

  28. #28

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    12

    Re: Help with calculate button

    For the time being, I am done with the Straight Line method; I have moved on to the Units Of Production method. Here is the code:

    Code:
    Private Sub CalculateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
            'Declaring variables
            Dim InitialCost As Integer = 0
            Dim Salvage As Integer = 0
            Dim TotalUnitsExpected As Integer = 0
            Dim UnitsProductionInPeriod As Integer = 0
            Dim DepreciableCost As Decimal = 0
            Dim DepreciationPerUnit As Decimal = 0
            Dim DepreciationForPeriod As Decimal = 0
    
            'Validating data
            Integer.TryParse(InitialCostTextBox.Text, InitialCost)
            Integer.TryParse(SalvageTextBox.Text, Salvage)
            Integer.TryParse(TotalUnitsExpectedTextBox.Text, TotalUnitsExpected)
            Integer.TryParse(UnitsProductionInPeriodTextBox.Text, UnitsProductionInPeriod)
            Decimal.TryParse(DepreciationPerUnitTextBox.Text, DepreciationPerUnit)
            Decimal.TryParse(DepreciationForPeriodTextBox.Text, DepreciationForPeriod)
    
            'Calculate depreicable cost
            DepreciableCost = InitialCost - Salvage
    
            'Calculate depreciation per unit; cannot divide by 0
            If TotalUnitsExpected = 0 Then
                MsgBox("Cannot divide by 0.")
            Else
                DepreciationPerUnit = DepreciableCost / TotalUnitsExpected
            End If
    
            'Calculate Depreciation for period
            DepreciationForPeriod = DepreciationPerUnit * UnitsProductionInPeriod
    
            'Display output
            DepreciationPerUnitTextBox.Text = DepreciationPerUnit.ToString("N2")
            DepreciationForPeriodTextBox.Text = DepreciationForPeriod.ToString("N2")
    Here is the test data. When I multiply 5.29 by 4500, I get 23,805 on my calculator, but when I divide the salvage (18500) by the total units expected (3500), I get a long decimal; when I multiply that long decimal by 4500, I get 23785.71.
    Attached Images Attached Images  

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width