我正在用 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/