Home > database >  Error System.InvalidCastException: 'Conversion from string "" to type 'Integer&#
Error System.InvalidCastException: 'Conversion from string "" to type 'Integer&#

Time:11-09

I'm trying to open a file that I already add to my TreeView control by clicking it twice, it should appears in a DataGridView control, when a I do it, it shows me the next error:

System.InvalidCastException: 'Conversion from string "Book1.csv" to type 'Integer' is not valid.'

At the Direccion variable, I'm not pretty sure, what it happening. Does any one could orient me? Please.

Public Sub TV_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As 
TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick

        Dim NombreNodo As String = TV.SelectedNode.Text

        Dim parseCSV As String

        Dim tstSeq() As String

        Dim Direccion As String = My.Computer.FileSystem.CurrentDirectory(NombreNodo)

        'Dim x As String = Path.GetFullPath(NombreNodo)

        'MessageBox.Show(Direccion)

        tstSeqDataGrid.Rows.Clear()

        Using FileSystem As FileStream = File.Open(Direccion, FileMode.Open, FileAccess.Read)
            Dim TestReader As New System.IO.StreamReader(FileSystem)

            Do While TestReader.Peek <> -1
                parseCSV = TestReader.ReadLine()
                tstSeq = parseCSV.Split(",")
                tstSeqDataGrid.Rows.Add(tstSeq)
                TstSequenceLoaded = True
            Loop

            TestReader.Close()
            FileSystem.Close()
        End Using

    End Sub

CodePudding user response:

I am assuming that the TreeView is loaded with file names and those files are located in the directory where the code is running. You can see the value of Direccion in the Immediate Window. Using Debug.Print instead of a message box saves you from the embarrassment of forgetting to remove the message box in the production code. The Debug.Print will just be removed.

I returned an array of lines in the file with ReadAllLines. Then loop through the lines as you did.

With Option Strict On (as it should be) you need to add the lower case c following "," so the compiler knows you intend it as a Char not a String.

Public Sub TV_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick
    Dim Direccion = My.Computer.FileSystem.CurrentDirectory & TV.SelectedNode.Text
    Debug.Print(Direccion)
    tstSeqDataGrid.Rows.Clear()
    Dim lines = File.ReadAllLines(Direccion)
    For Each line In lines
        Dim tstSeq = line.Split(","c)
        tstSeqDataGrid.Rows.Add(tstSeq)
    Next
    TstSequenceLoaded = True
End Sub
  • Related