c# - Richtextbox 行数

标签 c# winforms count richtextbox lines

我正在用 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";
            }
        }
    }

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

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

最佳答案

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

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

确保将其分配给 TextChanged 事件。

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

关于c# - Richtextbox 行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17520642/

相关文章:

c# - 将数字附加到整数并确保每个数字的总和以 1 结尾

mysql - 选择日期相等且 ID 相等的行,并将这些行计为一个

regex - 具有计数和条件的不同值 mongoDB

C# - AsEnumerable 示例

c# - 带有更新面板 : problem with chrome 的 PopupControlExtender

c# - 请求越多意味着从缓存对象中读取的速度越慢?

c# - 读取并解析 JSON 数据

c# - 如何在 C# Windows 窗体中使用 *** 在文本框中写入密码?

c# - C#中的线程安全数据库访问

ios - 如何在 swift 中使用文本字段文本 "Amount"向表格 View 添加额外的行