Search code examples
vb.netopenfiledialog

Opening a file with Visual Basic


The 'reader' within the if statement is showing

Expression is not a method

Dim reader As New CSVReader

OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
    reader(OpenFileDialog2.FileName)
    reader.DisplayResults(DataGridView1)
    'Return OpenFileDialog2.FileName
Else
End If

I moved the Dim and it worked.

OpenFileDialog2.InitialDirectory = "a:"
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
    Dim reader As New CSVReader(OpenFileDialog2.FileName)
    reader.DisplayResults(DataGridView1)
    'Return OpenFileDialog2.FileName
Else
End If

Solution

  • On this line:

    reader(OpenFileDialog2.FileName)
    

    You're trying to call a constructor on an object that is already constructed. That's not possible, so the VB compiler is interpreting this as you trying to call the reader object as if it were a function.

    Just don't declare the reader until you have the filename, so that you can pass the name to the constructor when you actually construct it, like so

        OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
        OpenFileDialog2.RestoreDirectory = True
        If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
    
            Dim reader As New CSVReader(OpenFileDialog2.FileName)
            reader.DisplayResults(DataGridView1)
            'Return OpenFileDialog2.FileName
        Else
        End If