Forum Discussion

Marco's avatar
Marco
Contributor II
2 years ago

Create CSV FILE

Hi Everyone. I am creating a CSV file with the information from a datatable. The problem is that it generates the file with the columns but without the datatable information. I wanted to know if th...
  • JackLacava's avatar
    JackLacava
    2 years ago

    I suspect your problem might lie in the checks you do with dt.Rows.Count. In a number of situations, that property doesn't work as expected. I would suggest to just loop on rows; if you want to enforce your "limit", keep track of iterations and then break out:

    ' it's bad practice to mess with stuff passed as parameter, let's wrap it...
    Dim realLimit as Integer = -1
    if limit > 0 then realLimit = limit
    ' keep an iteration index
    Dim curr As Integer = 0
    ' and we're off
    For Each row As DataRow In dt.Rows
       If curr >= realLimit Then
          Exit For
       Else
          curr += 1
       End If
       ' ... turn your row into a string etc etc
    next

    The other den of dragons is that check on column names, which might be case sensitive or fail on minimal differences. At a minimum, I would turn that ColumnName to all lowercase or all uppercase, and ensure the elements in that list have had the same treatment.

    Beyond that, I would check that your datatable actually  contains data, particularly if it came from some .Clone() operation or similar.

    Hope that helps!