Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Error: Input String Was Not In Correct Format

Posted on 2015-02-20
9
Medium Priority
?
52 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Integration Management Part 2
Suggested Courses

963 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