Conversion error in the array of a . csv file to a datatable

Asked

Viewed 48 times

1

I’m trying to pass the data from a file. csv to a datatable and the code seems to be all ok but I’ve been back from this error for quite some time and don’t know how to fix it.

I have two columns in my . csv file and a string type another integer type and the error from what I realized is giving in the first line in which the "ATID" is not entire in this first line being that the rest is a whole number and I do not know how to solve thanks help. I tried to make conversions and it didn’t work (I may have done 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);
                }

        }

Erro/Debug

2 answers

0

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

The code will look like this:

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

I suggest to make a treatment if errors occur in the casting.

  • http://prntscr.com/klc4kg, what kind of treatment you are talking about,

  • Try using this: dr["Atid"] = Convert.Toint32(lineitems[1]);

  • http://prntscr.com/klfa7u , keeps trowing the error xd, i already tryed that before but didnt work, i realy dont know how to fix this

0

Using a check with tryParse it is possible to check this before 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
         }
}
  • It didn’t work, I put this command inside while , but it keeps reading the first line, I’ll post screenshot http://prntscr.com/klc34b

  • I modified the answer, only adapt it to your case now. Then you will not have an error, as you will only try to use the value if tryParse returns true. See if he sees you now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.