Error converting an array from a .csv file to a datatable

1

I have tried to pass the data from a .csv file to a datatable and the code seems to be all ok but I have been back from this error for quite some time and I do not know how to resolve it.

I have two columns in my .csv file and a string type another integer type and the error by what I realized is to give in the first line in which the "ATID" is not integer in that first line being that the rest is a whole number and I do not know how to solve thanked help. I've already tried converting and it did not work (I may have gone wrong, some help is welcome).

Example:

PPID; ATID

asd; 1

asd; 2

asd; 3

dsa; 4

erf; 5

Error: System.ArgumentException: 'Input string was not in a correct format.Couldn't store < # assetId # > in AtId Column. Expected type is Int32. '

Code:

     using (StreamReader sr = new 
     StreamReader(@"C:Pathfile....csv"))
        {
            var datatable = new DataTable();
            datatable.Columns.Add("PPId", typeof(string));
            datatable.Columns.Add("AtId", typeof(int));
            string line;


                while ((line = sr.ReadLine()) != null)
                {

                    System.Diagnostics.Debug.WriteLine(line + "\n");
                    string[] lineitems = line.Split(";");
                    DataRow dr = datatable.NewRow();
                    dr["PPId"] = lineitems[0];
                    dr["AtId"] = lineitems[1]; 
                    datatable.Rows.Add(dr);
                }

        }

    
asked by anonymous 21.08.2018 / 01:20

2 answers

0

You need to do a cast on the line where you save the value in the datatable to save it in the correct format.

The code looks like this:

dr["AtId"] = (int) lineitems[1];

I suggest a treatment if casting errors occur.

    
21.08.2018 / 04:35
0

Using a check with tryParse you can check this before the error:

while (true)
{
         string[] lineItems = line.Split(';');

         if (int.TryParse(lineItems[1], out int result))
         {
                //So entrará aqui se o valor puder ser convertido. Caso sim, pode já usar a variavel com nome result, criada acima
         }
}
    
21.08.2018 / 13:26