为什么这个{“对象引用未设置为对象的实例。”}?

时间:2015-03-12 05:45:32

标签: vb.net

Private Sub TextFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextFileToolStripMenuItem.Click

        fd.Filter = "Text Files (*.txt)|*.txt"
        If fd.ShowDialog() = DialogResult.OK Then
            FileName = fd.FileName
            Ext = IO.Path.GetExtension(FileName)
            'read file
            If System.IO.File.Exists(FileName) = True Then
                Dim objReader As New System.IO.StreamReader(FileName)
                Do While objReader.Peek() <> -1
                    TextLine = TextLine & objReader.ReadLine & vbNewLine
                Loop
                TextFile.Text = TextLine
            Else
                MsgBox("File Does Not Exist")
            End If
            Me.BtnSort.Enabled = True
            Me.BtnDestroy.Enabled = True
            'counter = counter + 1
        End If
End Sub

2 个答案:

答案 0 :(得分:0)

我的猜测是名为fd的引用设置为null(无),因此您需要实例化一个新的OpenFileDialog并将其分配给引用:

fd = New OpenFileDialog()

因为您似乎想要阅读文件的整个文本,所以您可以缩短此代码(File.Exists allready返回一个布尔值,因此您不需要与true进行比较):

If System.IO.File.Exists(FileName) Then
    TextLine = TextLine & System.IO.File.ReadAllText(FileName)
    TextFile.Text = TextLine
Else

答案 1 :(得分:0)

您需要在使用之前为fd创建一个实例。也许在构造函数或它的声明中:

Private fd As New Form1