c#如何在richtextbox中只更新一行文本? [英] c# how can I update just one line text in richtextbox?

查看:111
本文介绍了c#如何在richtextbox中只更新一行文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何只更新富文本框中的一行文本?

how can I update just one line text in richtextbox?

String[] lines = richTextBox8.Lines;
lines[2] += " ";
richTextBox8.Lines = lines;

我正在使用此代码部分来更新富文本框的第二行,但它会扫描我所有的富文本框行并且需要很多次.

I am using this code part for update second line of richtextbox but it scans all my richtextbox lines and it takes many times.

所以我想更新 1 行的行文本.

so I want to update line text for 1 line.

我该怎么做?

推荐答案

请注意,您绝不能直接触摸 TextLines或者之前的所有格式都搞砸了.

Note that you must never touch the Text or the Lines directly or all previous formatting gets messed up.

这里有一个函数可以解决问题而不会弄乱格式:

Here is a function that will solve the problem without messing up the formatting:

void changeLine(RichTextBox RTB, int line, string text)
{
    int s1 = RTB.GetFirstCharIndexFromLine(line);
    int s2 = line < RTB.Lines.Count() - 1 ?
              RTB.GetFirstCharIndexFromLine(line+1) - 1 : 
              RTB.Text.Length;        
    RTB.Select(s1, s2 - s1);
    RTB.SelectedText = text;
}

注意 C# 中的编号是零基数,因此要更改第一行,请调用 changeLine(yourrichTextBox, 0, yourNewText);

Note the in C# the numbering is zero beased, so to change the 1st line you call changeLine(yourrichTextBox, 0, yourNewText);

要仅修改(而不是替换)该行,您只需访问 Lines 属性;只要确保永远不要改变

To only modify (not replace) the line you can simply access the Lines property; just make sure never to change it!

所以要在第 2 行添加一个空格,您可以这样写:

So to add a blank to the 2nd line you can write:

changeLine(yourrichTextBox, 1, yourrichTextBox.Lines[1] + " ");

这篇关于c#如何在richtextbox中只更新一行文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆