Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I want to calculate total. For this I am using following code undertxtDisc_TextChanged event.



qty = Convert.ToInt32(txtQty.Text)
        rate = Convert.ToInt32(txtRate.Text)
        disc = Convert.ToInt32(txtDisc.Text)

        total = qty * rate
        amt = total / disc
        total1 = total - disc

        txtAmt.Text = Convert.ToInt32(total1)


Code calculate correct total when i put disc > 0, i.e If I use disc = 0 then system throws an error :Arithmetic operation resulted in an overflow.

Another problem is If first time I put disc = 12 & before move forward I changed it to 10 then system throws an error : Input string is not in correct format.
Posted
Updated 10-Jan-13 3:58am
v2

You must ensure all input values were correct before performing calculation.
I suggest TryParse instead Try Catch block

VB
If Integer.TryParse(txtQty.Text, qty) AndAlso Integer.TryParse(txtRate.Text, rate) AndAlso Integer.TryParse(txtDisc.Text, disc) AndAlso (disc > 0) Then
    ' Do calculation here
    total = qty * rate
    amt = total / disc ' I suggest: amt = total \ disc
    total1 = total - disc
    txtAmt.Text = Convert.ToInt32(total1).ToString()
Else
    ' Something wrong in input parameter
    ' Do not calculate, you can give a MessageBox to tell user
End If
 
Share this answer
 
Because you are dividing by zero?

Try:

VB
If total <> 0 And disc <> 0 Then
        amt = total / disc
Else
        amt = 0
End If


I don't get what you mean by the second question, '& before move forward I changed it to 10 ' - can you explain in more detail?
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900