Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

System.FormatException: 'Input string was not in a correct format.' c# complete beginner

give other advice on how to improve the code.
when I launch the program, and I select the second option and put the info in, it comes up with error.

 static void InsertRecord()
    {
        records.Add(" name"); // 0
        records.Add(" name");  // 1
        records.Add(" name");  //2
        Console.WriteLine("Please enter first name");
        string fName = Console.ReadLine();
        Console.WriteLine("Please enter Last name");
        string lName = Console.ReadLine();
        int loc = Convert.ToInt32(Console.ReadLine()); // this line has the error
        if (loc > records.Count)
        {
            Console.WriteLine("Location out of range");
        }
        else
        {
            records.Insert(loc, fName + lName);
        }
        Console.ReadKey();
    } 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of using Convert.ToInt32, use Int32.TryParse, which:

Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.

For documentation, please have a look here.

The benefit of using that method instead of Convert.ToInt32 is that it will not throw any exception, when the input isn’t the expected one. It will just return false, indicating that the parse failed.

So we have to delete the following line:

int loc = Convert.ToInt32(Console.ReadLine());

and try the following:

if (Int32.TryParse(Console.ReadLine(), out int loc))
{
    if (loc > records.Count)
    {
        Console.WriteLine("Location out of range");
    }
    else
    {
        records.Insert(loc, fName + lName);
    }
}

You could also add an else statement in the above, for the inputs that parsing fails and inform the user of your application that the input wasn’t the expected one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading