Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input string was not in a correct format

Tags:

c#

parsing

I have a small problem here. When I tried to do the following steps,

string set1="123.10,134.40";
string set2="17,134"; 
List<string> List1 = new List<string>(set1.Split(','));
List<string> List2 = new List<string>(set2.Split(','));

var QueryResult = from D1 in List1 
                  from E1 in List2
                  select new
                  {
                      D1,
                      E1
                  };
DataTable tempDT = new DataTable();
tempDT.Columns.Add("Data1", typeof(int));
tempDT.Columns.Add("Data2", typeof(string));

foreach (var item in QueryResult)
{
    tempDT.Rows.Add(new object[] {Convert.ToInt32(item.E1.ToString()),
    Convert.ToString(item.D1.ToString()) });
}

When I try to add those values to the tempDT I am getting an exception:

Input string was not in a correct format.

How do I fix this issue?

like image 365
Pradeep Avatar asked Jul 11 '26 09:07

Pradeep


2 Answers

It is because you are using Convert.ToInt32 on a string that contains a decimal character.

like image 174
Jordan Parmer Avatar answered Jul 14 '26 23:07

Jordan Parmer


The code you posted worked just fine, so it means the problem is with your real data.

Most likely, you have something like this:

string set2="17,134,,20"; 

Meaning empty item which will crash the code.

Remove such empty items with:

List<string> List2 = new List<string>(set2.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries));

To be totally safe from that error, use TryParse instead:

int e1;
foreach (var item in QueryResult)
{
    if (Int32.TryParse(item.E1, out e1))
    {
        tempDT.Rows.Add(new object[] { e1, item.D1 });
    }
}

This will just ignore any invalid values, not adding them to the data table.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!