Solved

Error: Input String Was Not In Correct Format

Posted on 2015-02-20
9
45 Views
Last Modified: 2015-02-28
Hi,

I have an app to add coins, they need to equal up to $2.00. If I enter in 8 quarters, which is 2 dollars and leave the pennies, nickels and dimes field blank, I get a  error: Input String Was Not In Correct Format.

Any clue why?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoinApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            pennyTextBox.Text = "";
            nickelTextBox.Text = "";
            dimeTextBox.Text = "";
            quarterTextBox.Text = "";
            totalValueLabel.Text = "";

            pennyTextBox.Focus();
        }

        private void calculateButton_Click(object sender, EventArgs e)
        {
            try
            {
                const decimal PENNY_VALUE = 0.01m;
                const decimal NICKEL_VALUE = 0.05m;
                const decimal DIME_VALUE = 0.10m;
                const decimal QUARTER_VALUE = 0.25m;
                const decimal TOTAL = 2.00m;
               decimal total = 0.0m;



                int totalPenny, totalNickel, totalDime, totalQuarter;

                totalPenny = int.Parse(pennyTextBox.Text);
                totalNickel = int.Parse(nickelTextBox.Text);
                totalDime = int.Parse(dimeTextBox.Text);
                totalQuarter = int.Parse(quarterTextBox.Text);

                if (totalPenny <=0)
                {
                    MessageBox.Show("Number of pennies must be greater than 0");
                }
                else 
                {
                    total += (totalPenny * PENNY_VALUE);       
                }
               if (totalNickel <=0)
                {
                    MessageBox.Show("Number of nickels must be greater than 0");               
                }
               else
               {
                   total += (totalNickel * NICKEL_VALUE);
               }

                if (totalDime <= 0)
                {
                    MessageBox.Show("Number of dimes must be greater than 0");   
                }
                else
                {
                    total += (totalDime * DIME_VALUE);
                }
                if (totalQuarter <= 0)
                {
                    MessageBox.Show("Number of quarters must be greater than 0");   
                    
                }
                else
                {
                    total += (totalQuarter * QUARTER_VALUE);
                }

                if (total == TOTAL)
                {
                    totalValueLabel.Text = total.ToString("c");
                    winnerLooserLabel.Text = ("Congrats");
                }
                else
                {

                    totalValueLabel.Text = total.ToString("c"); 
                    winnerLooserLabel.Text = ("Try Again");
                }

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

Open in new window

0
Comment
Question by:Computer Guy
  • 5
  • 4
9 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40622581
As the documentation for int.Parse states:

In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed.

You need to test the value before you try to convert it. You can actually do both at the same time via int.TryParse.
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40622862
Ok, great!

This is what I came up with to replace it.
Two questions.

1. How do I handle invalid characters (letters, ect?
2. Is this clean / efficient code?

                const decimal PENNY = 0.01m;
                const decimal NICKEL = 0.05m;
                const decimal DIME = 0.10m;
                const decimal QUARTER = 0.25m;
                const decimal TOTAL = 2.00m;

                decimal total = 0m;


                int totalPenny, totalNickel, totalDime, totalQuarter;

                    if (int.TryParse(pennyTextBox.Text, out totalPenny) == true)
                    {
                        total += totalPenny * PENNY;
                    }

                    if (int.TryParse(nickelTextBox.Text, out totalNickel) == true)
                    {
                        total += totalNickel * NICKEL;
                    }

                    if (int.TryParse(dimeTextBox.Text, out totalDime) == true)
                    {
                        total += totalDime * DIME;
                    }

                    if (int.TryParse(quarterTextBox.Text, out totalQuarter) == true)
                    {
                        total += totalQuarter * QUARTER;
                    }
                    totalValueLabel.Text = total.ToString("c");

                    
                if (total == TOTAL)
                    {
                        MessageBox.Show("Congratulations, you have the correct number of coins");
                    }
                    else if (total > TOTAL)
                    {
                        MessageBox.Show("The number of coins you entered is more than " + TOTAL.ToString("c") + " Try again");
                    }
                    else if (total < TOTAL)
                    {
                        MessageBox.Show("The number of coins you entered is less than " + TOTAL.ToString("c") + " Try again");
                    }

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40622952
1. How do I handle invalid characters (letters, ect?
Show a MessageBox? Change the background color of the TextBox to red? It's up to you. What is your requirement?

2. Is this clean / efficient code?
It looks fine to me. Focus on readable code first. Worry about performance once it becomes an issue.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 3

Author Comment

by:Computer Guy
ID: 40622960
Should the box be per field? So if they enter in abc in nickel and dime it would show twice?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40622964
That's a decision you would have to make. But in terms of user experience, it would get tiresome having to click multiple MessageBox buttons every time I put in bad input. You might consider either tallying up all of the error messages, and then showing the complete list of errors in one MessageBox, or you might consider using the ErrorProvider, which gives indication of errors without really getting in the user's way.
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40623493
Hi,

Ok, so I tried this and if it is null, it shows the message box. It does not need to be a required field. If the value is an integer or blank, do the math or if there are invalid characters, then show the message box.

                if (int.TryParse(pennyTextBox.Text, out totalPenny) == true)
                {
                    total += totalPenny * PENNY_VALUE;
                }
                else
                {
                    MessageBox.Show("Please enter a valid number of pennies.");
                }

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40623675
I don't understand the question.
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40623729
Ok. So with the code I recently posted
It shows the message box when the penny text box is empty or has a letter in it.

I don't want it to show the message box if there is nothing in the text box. Show only if it is a letter
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40623735
if (!string.IsNullOrWhitespace(pennyTextBox.Text) && int.TryParse(pennyTextBox.Text, out totalPenny) == true)

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question