【问题标题】:IndexOutOfRangeException - RichTextIndexOutOfRangeException - 富文本
【发布时间】:2015-01-02 08:30:29
【问题描述】:

我有一个 RichTextBox (txt) 和一个 OpenFileDialog (Open1)。当我尝试以下操作时,我在指定的行上有一个 IndexOutOfRangeException:

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
    If (Open1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
        fName = Open1.FileName
        txt.LoadFile(fName, RichTextBoxStreamType.PlainText)
        Dim i As Integer = 0
        While i < txt.Lines.Length
            AnalyseLine(i)
            i = i + 1
        End While
    End If
End Sub

Private Sub AnalyseLine(ByVal line As Integer)
    Select Case txt.Lines(line).Substring(0, 1) '''' EXCEPTION ON THIS LINE ''''
        ' [...]
    End Select
End Sub

无论 line 变量值多少,每次都会抛出异常。 我真的不明白为什么,因为它对每个文本文件都抛出相同的异常。此外,似乎这个问题只有在打开新文件时才会出现,因为使用以下代码,它可以正常工作......

Private Sub txt_TextChanged(sender As Object, e As EventArgs) Handles txt.TextChanged
    AnalyseLine(txt.GetLineFromCharIndex(txt.GetFirstCharIndexOfCurrentLine))
End Sub

【问题讨论】:

  • 我得到了它的工作,通过用 txt.Text = System.IO.File.ReadAllText(fName) 替换 txt.LoadFile(fName, RichTextBoxStreamType.PlainText) 但我仍然不明白......

标签: vb.net richtextbox selection


【解决方案1】:

一行可能只是一个空字符串(我猜是最后一行),所以检查一下:

Private Sub AnalyseLine(ByVal line As Integer)
  If txt.Lines(line).Length > 0 Then
    Select Case txt.Lines(line).Substring(0, 1)
      ' [...]
    End Select
  End If
End Sub

【讨论】:

  • 不,它不起作用,现在它在 If 语句中抛出异常
【解决方案2】:

AnalyseLine 有问题。 1)你不应该假设 line 是有效的,应该检查它是否在 0 的范围内......如果它在 while 之外使用它可能会失败。 2) 如果 txt 为空怎么办。它会失败。 3)您确实需要检查长度以查看它是否> 0 4) 为什么使用子字符串而不是数组索引 [0]?您正在使用一种仅获取 1 个字符的方法。编码错误。

代码问题太多。它不会通过同行评审。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多