Solved

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Posted on 2016-10-07
5
49 Views
Last Modified: 2016-10-07
private void TxtMarks1030_TextChanged(object sender, EventArgs e)
        {

            Int32 marks1030 = Convert.ToInt32(TxtMarks1030.Text);

            if (marks1030 >= 101)
            {
                LblGrade1030.Text = "Please enter less than 100";
            }
            else if (marks1030 >= 90)
            {
                LblGrade1030.Text = "A";
            }
            else if (marks1030 >= 80)
            {
                LblGrade1030.Text = "B";
            }
            else if (marks1030 >= 65)
            {
                LblGrade1030.Text = "C";
            }
            else if (marks1030 >= 50)
            {
                LblGrade1030.Text = "D";
            }
            else if (marks1030 >= 40)
            {
                LblGrade1030.Text = "E";
            }
            else
            {
                LblGrade1030.Text = "Fail";
            }
        }
0
Comment
Question by:the student
  • 2
  • 2
5 Comments
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41834431
This exception occurs because the string being presented to convert is not convertable to an integer; e.g -
using System;

namespace EE_Q28975134
{
	class Program
	{
		static string grade1 = "90";
		static string grade2 = "I am not the number 90";

		static void Main(string[] args)
		{
			GetGrade(grade1);
			Console.WriteLine();
			GetGrade(grade2);
			Console.ReadLine();
		}

		private static void GetGrade(string value)
		{
			try 
			{
				int grade = Convert.ToInt32(value);
				if (grade > 100)
					Console.WriteLine("Please enter a grade less than 100.");
				else
					Console.WriteLine("Your test score - [{0}] produces a grade of: {1}", value, grade >= 90 ? "A" : grade >= 80 ? "B" : grade >= 65 ? "C" : grade >= 50 ? "D" : grade >= 40 ? "D" : "F");
			}
			catch (Exception ex)
			{
				Console.WriteLine("The value entered cannot convert to an integer, grade cannot be calculated.  {0}", ex.Message);
			}
		}
	}
}

Open in new window

Produces the following output -Capture.JPG
To correct you can use a try...catch block as I demonstrated:
private void TxtMarks1030_TextChanged(object sender, EventArgs e)
{
	try
	{
		Int32 marks1030 = Convert.ToInt32(TxtMarks1030.Text);
		if (marks1030 >= 101)
			LblGrade1030.Text = "Please enter less than 100";
		else if (marks1030 >= 90)
			LblGrade1030.Text = "A";
		else if (marks1030 >= 80)
			LblGrade1030.Text = "B";
		else if (marks1030 >= 65)
			LblGrade1030.Text = "C";
		else if (marks1030 >= 50)
			LblGrade1030.Text = "D";
		else if (marks1030 >= 40)
			LblGrade1030.Text = "E";
		else
			LblGrade1030.Text = "Fail";
	}
	catch (Exception)
	{
		LblGrade1030.Text = "Cannot convert grade";
	}
}

Open in new window

Or you could use a different method to convert your field's value, a method that does not throw an exception.  Something like Int32.TryParse.  Since it returns a boolean value that siginifies the conversion was successful, you would change your method to do this:
private void TxtMarks1030_TextChanged(object sender, EventArgs e)
{
	Int32 marks1030;
	if(Int32.TryParse(TxtMarks1030.Text, out marks1030))
	{
		if (marks1030 >= 101)
			LblGrade1030.Text = "Please enter less than 100";
		else if (marks1030 >= 90)
			LblGrade1030.Text = "A";
		else if (marks1030 >= 80)
			LblGrade1030.Text = "B";
		else if (marks1030 >= 65)
			LblGrade1030.Text = "C";
		else if (marks1030 >= 50)
			LblGrade1030.Text = "D";
		else if (marks1030 >= 40)
			LblGrade1030.Text = "E";
		else
			LblGrade1030.Text = "Fail";
	}
	else
	{
		LblGrade1030.Text = "Cannot convert grade";
	}
}

Open in new window


Proof of concept rewriting the above example:
using System;

namespace EE_Q28975134
{
	class Program
	{
		static string grade1 = "90";
		static string grade2 = "I am not the number 90";

		static void Main(string[] args)
		{
			GetGrade(grade1);
			Console.WriteLine();
			GetGrade(grade2);
			Console.ReadLine();
		}

		private static void GetGrade(string value)
		{
			int grade;
			if (int.TryParse(value, out grade))
			{
				if (grade > 100)
					Console.WriteLine("Please enter a grade less than 100.");
				else
					Console.WriteLine("Your test score - [{0}] produces a grade of: {1}", value, grade >= 90 ? "A" : grade >= 80 ? "B" : grade >= 65 ? "C" : grade >= 50 ? "D" : grade >= 40 ? "D" : "F");
			}
			else
			{
				Console.WriteLine("The value entered cannot convert to an integer, grade cannot be calculated.");
			}
		}
	}
}

Open in new window

Now produces a very similar output (minus the exception message ofcourse) -Capture.JPG
-saige-
0
 

Author Comment

by:the student
ID: 41834444
Thank you, it_saige.

It was very helpful now it's working fine. You made my day. This was the part of assignment. thank you again
0
 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
ID: 41834461
Test for null or empty string.and validated input.
 private void TxtMarks1030_TextChanged(object sender, EventArgs e)
        {
            
            if (string.IsNullOrEmpty(TxtMarks1030.Text) == false)
            {
                try
                {
                    Int32 marks1030 = Convert.ToInt32(TxtMarks1030.Text);
                    if (marks1030 >= 101) { LblGrade1030.Text = "Please enter less than 100"; }
                    else if (marks1030 >= 90) { LblGrade1030.Text = "A"; }
                    else if (marks1030 >= 80) { LblGrade1030.Text = "B"; }
                    else if (marks1030 >= 65) { LblGrade1030.Text = "C"; }
                    else if (marks1030 >= 50) { LblGrade1030.Text = "D"; }
                    else if (marks1030 >= 40) { LblGrade1030.Text = "E"; }
                    else { LblGrade1030.Text = "Fail"; }
                }
                catch {
                    LblGrade1030.Text = "You must enter an integer  from 0 to 100";
                }
            }
        }

Open in new window


Yet another method that uses tryparse
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            LblGrade1030.Text = "Enter an Integer from 0 to 100";
        }

        private void TxtMarks1030_TextChanged(object sender, EventArgs e)
        {
            Int32 marks1030;
            LblGrade1030.Text = "Enter an Integer from 0 to 100";
            if (int.TryParse(TxtMarks1030.Text, out marks1030))
            {

                if (marks1030 >= 101) { LblGrade1030.Text = "Please enter less than 100"; }
                else if (marks1030 >= 90) { LblGrade1030.Text = "A"; }
                else if (marks1030 >= 80) { LblGrade1030.Text = "B"; }
                else if (marks1030 >= 65) { LblGrade1030.Text = "C"; }
                else if (marks1030 >= 50) { LblGrade1030.Text = "D"; }
                else if (marks1030 >= 40) { LblGrade1030.Text = "E"; }
                else { LblGrade1030.Text = "Fail"; }
            }

        }
    }

}

Open in new window

0
 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
ID: 41834462
Should have refreshed the page first
2
 

Author Comment

by:the student
ID: 41834467
Thanks David Johnson
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
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, fr…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

757 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

20 Experts available now in Live!

Get 1:1 Help Now