none
[Resolved] String to Integer Conversion Error when reading file RRS feed

  • Question

  • Hello all,

    This programs attempts to read a textfile, spilt the strings delimited by ';', and change the BG color of the DataGridView accordingly.
    I have a conversion error when executing this code. But I'm not sure where the error lies.
    Please assist.




    Function loadCellColor()
            Dim i As Integer = 0        'Counter for Rows
    
            Dim ID As Integer                       'Store row ID value
            Dim colIndex As Integer                 'Store Column
            Dim colorString As String               'Store Color Code
    
            Dim FileToString As String = ""     'grab 1 line from file
            Dim split As String()               'divide line via ";" delimiter
            Dim filePath As String = "..\..\..\config\cellColor.txt"
            Dim filenum As Integer
    
            filenum = FreeFile()
    
            'Read from File
            Try
                FileOpen(filenum, filePath, OpenMode.Input)
                'Read Line by Line
                While Not EOF(filenum)
                    FileToString = LineInput(filenum)
                    split = Regex.Split(FileToString, ";")
                    ID = Convert.ToInt32(split(0))              'Store row ID value
                    colIndex = Convert.ToInt32(split(1))        'Store Column
                    colorString = split(2)                      'Store Color Code
    
                    System.Windows.Forms.MessageBox.Show(ID.ToString & " Column= " & colIndex.ToString & " color=" & colorString)
    
                    For i = 0 To ProjectsDataGridView.RowCount - 1
                        'Look for Matching Row ID
                        If ProjectsDataGridView.Rows(i).Cells(0).Value = ID Then
    
                            'Highlight the Cell
                            ProjectsDataGridView.Rows(i).Cells(colIndex).Style.BackColor = Color.FromArgb(CInt(colorString))
                            'Found the Cell, break loop and read next line
                            Exit For
    
                        End If
                    Next
    
                End While
    
                FileClose(filenum)
            Catch ex As Exception
                MessageBox.Show("File Error Occurred!" + vbCrLf + ex.ToString)
            End Try
    
            Return Nothing
    
    End Function

    The textfile looks like this:
    79;6;-16711808



    • Edited by wk89 Saturday, May 4, 2019 2:40 PM
    Saturday, May 4, 2019 6:38 AM

All replies

  • Hi,

    I have tried it and it is working fine for me. Maybe in your file has some spacing and it is breaking it.

    Try to debug it. And see how it loads the variables and in which Convert.ToInt32 it is breaking (in the split(0) or in the split(1))

    If you have whit spaces, you can use .Trim to fix it.

    eg:

    ID = Convert.ToInt32(split(0).Trim())              'Store row ID value
    colIndex = Convert.ToInt32(split(1).Trim())        'Store Column

    

    __________________________________

    If it helped you, mark as answer! Thank you.


    Saturday, May 4, 2019 9:31 AM
  • Hi,

    I realize the reason for error is because there is an extra empty line in my textfile

    79;6;-16711808 <Space>
    <Space>


    In my other code that Writes the file, I have a vbCrLf at end of line. This is needed to prevent the Data from writing into one single line.

    What can I do to solve this?

    'Prepare and open the Textfile
            Dim StringToFile As String = ""
            Dim filePath As String = "..\..\..\config\cellColor.txt"
            Dim filenum As Integer
            filenum = FreeFile()
    
            For i = 0 To ProjectsDataGridView.RowCount - 1
                For j = 0 To ProjectsDataGridView.ColumnCount - 1
                    'If backcolor is NOT White (NOT 0)
                    If ProjectsDataGridView.Rows(i).Cells(j).Style.BackColor.ToArgb.ToString <> "0" Then
    
                        'This Cell is highlighted
                        ID = ProjectsDataGridView.Rows(i).Cells(0).Value                                        'Get ID number
                        colIndex = j                                                                            'Get Column Index
                        colorString = ProjectsDataGridView.Rows(i).Cells(j).Style.BackColor.ToArgb.ToString()   'Get Color Code
    
                        'System.Windows.Forms.MessageBox.Show(ID.ToString & " Column= " & colIndex.ToString & " color=" & colorString)
    
                        '===============================================================================================================
                        'Overwrite to File (ID;colIndex;colorString)
                        Try
                            FileOpen(filenum, filePath, OpenMode.Output)
                            StringToFile &= ID.ToString & ";" & colIndex.ToString & ";" & colorString & vbCrLf    'each loop appends StringToFile
                            PrintLine(filenum, StringToFile)
                            FileClose(filenum)
    
                        Catch ex As Exception
                            MessageBox.Show("File Error Occurred!" + vbCrLf + ex.ToString)
                        End Try
                        '===============================================================================================================
    
                    End If
                Next
            Next

    Saturday, May 4, 2019 10:45 AM
  • You should use TextFieldParser class, set delimiter to a semi-colon, on each iteration of reading the file check the array, does it have enough elements? If so, can the ID be converted to an Integer using Integer.TryParse? If yes to all then you have a valid line and valid id then move on from there.

    If by chance you need to know the line count in the file to match against how many valid lines there are in the file then use

    Dim lineCount As Integer = IO.File.ReadAllLines("filename").Length

    Bottom line is TextFieldParser and Integer.TryParse make the task easier than how it's being done now.

    If all data was perfect we could parse the data in the file with one line of code e.g.

    Private Sub Demo()
        Dim data =
                (
                    From line In IO.File.ReadAllLines("..\..\..\config\cellColor.txt")
                    Where line.Length > 0 Let Items = line.Split(","c)
                    Select New With
                        {
                            .Id = CInt(Items(0)),
                            .StoreCode = CInt(Items(1)),
                            .ColorCode = Items(2)
                        }
                ).ToList
    End Sub

    Then using the data

        Private Sub Demo()
            Dim data =
                    (
                        From line In IO.File.ReadAllLines("..\..\..\config\cellColor.txt")
                        Where line.Length > 0 Let Items = line.Split(","c)
                        Select New With
                            {
                                .Id = CInt(Items(0)),
                                .StoreCode = CInt(Items(1)),
                                .ColorCode = Items(2)
                            }
                    ).ToList
    
            ' where 1 would be a value from your DataGridView cell value
            If data.FirstOrDefault(Function(item) item.Id = 1) IsNot Nothing Then
                ' stop 
            End If
        End Sub

    But rarely does this happen so we go back to TextFieldParser.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, May 4, 2019 12:11 PM
    Moderator
  • OMG, sorry for all the trouble.

    I found the solution.

    Just change PrintLine() to Print()

    Print(filenum, StringToFile)

    Saturday, May 4, 2019 2:33 PM
  • Hi,

    I am glad you have got your solution, we appreciated you  mark it as an answer.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 6, 2019 1:20 AM