简体   繁体   English

如何在richTextBox的索引0中的每一行附近添加数字?

[英]How can i add numbers near each line in index 0 in richTextBox?

for (int i = 0; i < richTextBox2.Lines.Length; i++)
{
    richTextBox2.Lines[i] = richTextBox2.Lines[i].Insert(0, i + " ");
}

Before that tried with the Insert: 在尝试插入之前:

richTextBox2.Lines[i].Insert(0, i + " ");

In both cases it's not adding any numbers. 在这两种情况下,都不会加任何数字。

For example if the lines are: 例如,如果这些行是:

Hello world
Hi
Hello

Then i want it to be now: 然后我希望它现在是:

1 Hello world
2 Hi
3 Hello

But the loop does nothing it's not adding any numbers. 但是循环不会执行任何操作,因为它不会添加任何数字。

You can't modifiy the single line in that way. 您不能以这种方式修改单行。 If you look at MSDN you will find this remark 如果您查看MSDN,您会发现这句话

By default, the collection of lines is a read-only copy of the lines in the TextBox. 默认情况下,行集合是TextBox中行的只读副本。 To get a writable collection of lines, use code similar to the following: textBox1.Lines = new string[] { "abcd" }; 要获得可写的行集合,请使用类似于以下代码:textBox1.Lines = new string [] {“ abcd”};

So the correct way to reach you goal is 因此,达到目标的正确方法是

string[]  lines = richTextBox2.Lines;

for (int i = 0; i < lines.Length; i++)
{
    lines[i] = (i+1) + " " + lines[i];
}
richTextBox2.Lines = lines;

You can try using Linq : 您可以尝试使用Linq

using System.Linq;

...

richTextBox2.Lines = richTextBox2
  .Lines
  .Select((line, index) => $"{index + 1} {line}")
  .ToArray();

please, avoid redrawing UI (esp. RichTextBox ) which can slow down your application, but build the data (lines, text) and then assign it in one go . 请避免重绘UI (尤其是RichTextBox ),这可能会降低您的应用程序的速度,但会生成数据(行,文本),然后一次性分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM