我正在创建一个工具,将文件读入字符串数组,然后在RichTextbox控件中显示字符串数组的所有行之前编辑每个数组索引的文本。
到目前为止,这是我的代码:
Private Sub btnOpen_Click(sender As Object, e As EventArgs) Handles btnOpen.Click
Dim ofd As New OpenFileDialog
ofd.FileName = ""
ofd.Title = "Open File"
If ofd.ShowDialog = DialogResult.OK Then
'read file
Dim reader As New StreamReader(ofd.FileName, Encoding.Default)
Dim line As String = Nothing : Dim counter As Integer = 0
Do
line = reader.ReadLine
readLines(counter) = line
counter += 1
Loop Until line Is Nothing
reader.Close() : counter = 0
'removing text from left
While counter < readLines.Length
readLines(counter) = readLines(counter).Substring(0, readLines(counter).Length - txtLimit.Text)
counter += 1
End While
counter = 0
'show result in RichTextBox
While counter < readLines.Length
rtBox.Text = rtBox.Text + readLines(counter) + vbNewLine
counter += 1
End While
ElseIf ofd.ShowDialog = DialogResult.Cancel Then
MsgBox("Operation Cancelled!")
Else
MsgBox("Unable to open file!")
End If
End Sub
在readLines(counter) = line
下面,counter += 1
,我收到此错误:
System.NullReferenceException:对象引用未设置为Object的实例
我做错了什么?
答案 0 :(得分:0)
我怀疑原始问题是readLines
数组没有正确初始化。代码尝试写入数组的末尾,而调试器由于某种原因在错误的行上显示问题。
仅Dim
数组是不够的。这只是设置一个引用变量,但该变量仍为null
/ Nothing
。您还必须创建New(提示)数组对象。
也就是说,这个功能可以减少很多。
Private Sub btnOpen_Click(sender As Object, e As EventArgs) Handles btnOpen.Click
Dim ofd As New OpenFileDialog
ofd.Title = "Open File"
Dim result As DialogResult = ofd.ShowDialog()
If result = DialogResult.Cancel Then
MsgBox("Operation Cancelled!")
Exit Sub
ElseIf result <> DialogResult.Ok
MsgBox("Unable to open file!")
Exit Sub
End If
Dim lines = File.ReadLines(ofd.FileName).Select(Function(line) line.Substring(0, line.Length - CInt(txtLimit.Text)) & vbNewLine)
For Each line As String In Lines
rtBox.Text &= line
Next
End Sub