Solved

Error: Input String Was Not In Correct Format

Posted on 2015-02-20
9
42 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

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…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now