4

I have one simple windows application in that amount Textbox is there. When i enter amount into amount textbox it will convert it to words in another textbox named txtrupees. Amount Textbox field maximum length is set to 11 places in that last 3 places .00.

My problem is now when i Enter amount with .00 it is working fine. But if i enter 11 places it will giving following Error:

System.OverflowException' occurred in mscorlib.dll Value was either too large or too small for an Int32.tried following code.

How can I prevent this kind of error?

private void txtamount_TextChanged(object sender, EventArgs e)
{
    if (txtamount.Text != string.Empty)
    {
        string[] amount = txtamount.Text.Split('.');
        if (amount.Length == 2)
        {
            int rs, ps;
            int.TryParse(amount[0], out rs);
            int.TryParse(amount[1], out ps);

            string rupees = words(rs);
            string paises = words(ps);
            txtrupees.Text = rupees + " rupees and " + paises + " paisa only ";
        }
        else if (amount.Length == 1)
        {
            string rupees = words(Convert.ToInt32(amount[0]));
            txtrupees.Text = rupees + " rupees only";
        }
    }
}
2
  • 1
    The error is self explanatory. Int32 only can hold values up to 2,147,483,647. If you try to parse a bigger value, it would throw that OverflowException Commented Apr 26, 2017 at 10:07
  • msdn.microsoft.com/en-us/library/y3d0kef1.aspx Commented Apr 26, 2017 at 10:12

2 Answers 2

6

The issue comes from Convert.ToInt32(amount[0]) where amount[0] can be almost anything, including being superior to Int.MaxValue or inferior to Int.MinValue which would cause an overflow.

Use int.TryParse(amount[0], out foo); and use foo:

else if (amount.Length == 1)
{
    int ps;
    if(int.TryParse(amount[0], out ps))
    {
        string rupees = words(ps);
        txtrupees.Text = rupees + " rupees only";
    }
    else
        txtrupees.Text = "Invalid number";
}

If you want to deal with bigger numbers, you can use Int64, Double or Decimal

Sign up to request clarification or add additional context in comments.

3 Comments

If it helped you, you can accept/upvote the answer of your choice. This is the StackOverflow wait to say 'Thanks', @vinnu
how to write validation for amount textbox it will allow only 8digits and 2 decimal places total 11.If i didn't enter decimal places it should allow 8 places.If i enter decimal it will take 11 digits .Please help me
@vinnu this is a different question you're asking. Post a new one explaining what you tried about the validation and why it doesn't work
1

a number that has 11 places is larger than a Int32 number. I suggest you should use int64 instead of int32 https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.