Solved

Error: Input String Was Not In Correct Format

Posted on 2015-02-20
9
40 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 74

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 74

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 74

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 74

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 74

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

746 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

10 Experts available now in Live!

Get 1:1 Help Now