Monday, 22 November 2010

C# Error: Input string was not in a correct format

You will receive a C# error �Input string was not in a correct format� , when you try to convert a string value into integer. To prevent this error either check the value of string is integer or not or keep conversion block inside try catch block.

other method is to use TryParse  to convert string to integer.

How to produce Code:

using System;
using System.Collections.Generic;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
        string str = "one";
        int i = Convert.ToInt32(str);    
        Console.WriteLine("Numeric Value is: " + i);
        Console.ReadLine();
        }
    }
}

C# Error: Input string was not in a correct format

How to prevent Error:

Method 1:

int i = 0;
    try
    {
        i = Convert.ToInt32(str);
    }
    catch (Exception ex)
    {
    }

 

Method 2:

Int32.TryParse(str,out i);

No comments:

Post a Comment