为 RichTextBox 制作行列表

Making a line list for a RichTextBox

我正在制作一个文本编辑器,我想像其他程序一样有一个行列表。 我写了这段代码(我使用 ListBox 控件来实现):

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
    On Error Resume Next
    If e.KeyCode = Keys.Back Then
        If TextBox1.Lines.Count > 1 Then
            ListBox1.Items.RemoveAt(ListBox1.Items.Count - 1)
        End If
    End If
    If e.KeyCode = Keys.Enter Then
        ListBox1.Items.Add(TextBox1.Lines.Count + 1)
    End If
End Sub

但是存在这些问题

我的行计数器从 1 开始

您的方法无法正常工作,因为您没有考虑到所有可能的情况,例如复制和粘贴,以及将所有退格键都计为一行删除,这显然是不准确的。更好的方法是使用 TextChanged 事件而不是 KeyDown 事件。然后,您可以跟踪变量中的行数,当它发生变化时,您可以更新 ListBox.

Private lineCount As Integer = 0

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If lineCount < TextBox1.Lines.Count Then
        For i As Integer = lineCount + 1 To TextBox1.Lines.Count
            ListBox1.Items.Add(i)
        Next
    ElseIf lineCount > TextBox1.Lines.Count Then
        For i As Integer = TextBox1.Lines.Count To lineCount - 1
            ListBox1.Items.Remove(i + 1)
        Next
    End If
    lineCount = TextBox1.Lines.Count
End Sub