简体   繁体   English

如何在richTextBox中添加新行而不在新行后留空格/空行?

[英]How can i add a new line to richTextBox without making space/empty line after the new line?

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string lastpadnum = padnumbers[padnumbers.Count - 1];
                int desiredLength = lastpadnum.Length;
                int nextnum = Convert.ToInt32(lastpadnum) + 1;
                string nextpadnum = nextnum.ToString().PadLeft(desiredLength, '0');
                padnumbers.Add(nextpadnum);
                richTextBox1.AppendText("\r\n" + nextpadnum);
            }
        }

This is working once if i scroll down to the bottom of the richtextbox and click on enter it will add a new line. 如果我向下滚动到richtextbox的底部,然后单击Enter,它将添加新的行,这将工作一次。 If the last line was 191 the new one will be 192. Or if last one was 000191 the new one will be 000192. 如果最后一行是191,则新行将是192。或者如果最后一行是000191,则新行将是000192。

But i have two problems: 但是我有两个问题:

The first is that this is working only if i click on enter after scrolled down to the bottom and adding new last line. 第一个是,只有当我向下滚动到底部并添加新的最后一行后单击Enter时,此方法才有效。 But if i want to add a new line and give it a number somewhere in the middle between two existing lines ? 但是,如果我要添加新行并在两个现有行之间的中间某个地方给它一个数字,该如何做? How then i renumber the whole lines ? 那我怎么给整行重新编号? For example if i click on enter key between lines 0033 and 0035 then the new line is 0034 but line 0034 that is already exist should be now 0035 and 0035 will be 0036... 例如,如果我单击0033和0035行之间的Enter键,则新行是0034,但已经存在的0034行现在应该是0035,而0035将是0036 ...

Second problem is that each time in the bottom i will click on enter it will make new line empty new line and then will add the line. 第二个问题是,每次在底部我都会单击Enter,它将使新行变为新行,然后添加该行。 I need the "\\r\\n" to make it new line but then next time i click enter it will first make new empty line. 我需要用“ \\ r \\ n”来换行,但是下次我单击Enter时,它将首先换成新的空行。 How can i avoid the empty line but that it will add a new line after the last one ? 我如何避免出现空行,但会在最后一行之后添加新行?

For your first question if you press enter in middle line it will add you new lines anyway at the bottom, so 0034 that exist will be 0035. But if you need to do something with this line where the caret position is you can look at this post . 对于第一个问题,如果您按中间行的Enter键,无论如何都会在底部添加新行,因此,存在的0034将是0035。但是,如果您需要对这行做一些插入标记位置的操作,则可以查看此行发布

For your second problem I checked your code and you just need to remove the \\r\\n from your code because when you hit enter you adding new line. 对于第二个问题,我检查了您的代码,您只需要从代码中删除\\ r \\ n,因为当您按下Enter键时,您需要添加新行。 If you want to keep the \\r\\n you can use 如果您想保留\\ r \\ n,可以使用

   e.SuppressKeyPress=true;

This will disable the new line that the enter key make. 这将禁用回车键产生的新行。

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

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