【问题标题】:Making a line list for a RichTextBox为 RichTextBox 制作行列表
【发布时间】:2021-04-01 10:30:05
【问题描述】:

我正在制作一个文本编辑器,我想要一个像其他程序一样的行列表。 我写了这段代码(我使用了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 开始,然后是 3,有时是 1,4

我的线路计数器从 1 开始

【问题讨论】:

    标签: vb.net winforms listbox richtextbox


    【解决方案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
    

    【讨论】:

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