Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Error: Input String Was Not In Correct Format

Posted on 2015-02-20
9
Medium Priority
?
51 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

Question has a verified solution.

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

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

670 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