Richtextbox 行数

Los*_*799 2 c# lines count richtextbox winforms

我正在用 C# 开发一个文本编辑器,并且正在尝试进行行数统计。

    private void updateNumberLabel()
    {
        Point pos = new Point(0, 0);
        int firstIndex = Document.GetCharIndexFromPosition(pos);
        int firstLine = Document.GetLineFromCharIndex(firstIndex);

        pos.X = ClientRectangle.Width;
        pos.Y = ClientRectangle.Height;

        int lastIndex = Document.GetCharIndexFromPosition(pos);
        int lastLine = Document.GetLineFromCharIndex(lastIndex);

        int actualLine = Document.GetLineFromCharIndex(actualPos);
        pos = Document.GetPositionFromCharIndex(lastIndex);

        if (lastLine != actualLine)
        {
            numberLabel.Text = "";
            for (int i = firstLine; i <= lastLine + 1; i++)
            {
                numberLabel.Text += i + 1 + "\n";
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

它工作正常,并在您编写行数时添加行数,但如果您删除一行,则只有在删除或再添加一行时它才会更新。

我想让它瞬间完成。如果删除一个,计数将立即减少。

Der*_*Ape 5

也许这太简单了,但是那又怎么样:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
  var lineCount = richTextBox.Lines.Count();
  numberLabel.Text = lineCount.ToString();
}
Run Code Online (Sandbox Code Playgroud)

确保将其分配给TextChanged事件。

如果这不是您所需要的,请添加一些您想要实现的更多信息。