Raj Raj - 1 year ago 116
ASP.NET (C#) Question

Input string was not in a correct format while doing ParseInt in C#

I am trying to do a Parse int in C# but I am getting the exception in the line

int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));
like below


"System.FormatException: Input string was not in a correct format.


Code is below:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string fromTo= "M5000C001";
int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));
int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
Console.WriteLine("FromTo" + mFrom);
}
}

Answer Source

Try this:

IndexOf will return the index of the character literal that you have requested.

string fromTo= "M5000C001";
int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C") - 1));
int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
Console.WriteLine("FromTo" + mFrom);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download