加入线

时间:2009-10-28 09:45:08

标签: c# richtextbox paragraph

在Windows窗体上,我有几行文字的RichTextBox。和表格上的一个按钮。

我喜欢当我点击那个按钮,在一行中加入所有行的文本框,但不是松散的文本样式(如字体系列,颜色等)

我无法使用替换,例如\ r \ n,而不是替换(Environment.NewLine,“”)........ : - ((

我也试过替换\ par和\ pard,但仍然没有运气.......

请帮助!!!


richTextBox1.Text = richTextBox1.Text.Replace(Environment.NewLine, "");

这个不好,因为有松散的字体定义(颜色,粗体,非粗线等)。

好的,再说一点......

我有RichTextBox控件,有4行文字:

line 1
line 2
line 3
line 4

第3行显示为红色。

我需要关注:

line 1 line 2 line 3 line 4

(并且“第3行”是以前的红色)。

当我尝试

richTextBox1.Text = richTextBox1.Text.Replace(Environment.NewLine,“”);

...我明白了:

line 1
line 2   
line 34

“第2行”为红色。

我该怎么做才能解决这个问题?

4 个答案:

答案 0 :(得分:1)

这将有效:

        // Create a temporary buffer - using a RichTextBox instead
        // of a string will keep the RTF formatted correctly
        using (RichTextBox buffer = new RichTextBox())
        {
            // Split the text into lines
            string[] lines = this.richTextBox1.Lines;
            int start = 0;

            // Iterate the lines
            foreach (string line in lines)
            {
                // Ignore empty lines
                if (line != String.Empty)
                {
                    // Find the start position of the current line
                    start = this.richTextBox1.Find(line, start, RichTextBoxFinds.None);

                    // Select the line (not including new line, paragraph etc)
                    this.richTextBox1.Select(start, line.Length);

                    // Append the selected RTF to the buffer
                    buffer.SelectedRtf = this.richTextBox1.SelectedRtf;

                    // Move the cursor to the end of the buffers text for the next append
                    buffer.Select(buffer.TextLength, 0);
                }
            }

            // Set the rtf of the original control
            this.richTextBox1.Rtf = buffer.Rtf;
        }

答案 1 :(得分:0)

TextBox控件有自己的查找和替换文本的方法。看一下这篇文章(这是VB.NET,但我希望你能得到这个想法):http://www.codeproject.com/KB/vb/findandriplace_rtb.aspx

答案 2 :(得分:-1)

我打赌你只是在文本字符串上调用Replace,你需要做的是这样的事情:

richTextBox1.Text = richTextBox1.Text.Replace(Environment.NewLine, "");

这里的关键是你需要将函数的结果分配给富文本框的文本,否则什么都不会发生。看,字符串是不可变的,每当你对一个字符串执行操作时,你必须将操作的结果分配给某些东西(即使原始变量也会起作用),否则没有任何反应。

答案 3 :(得分:-1)

我认为这有助于你:

StringBuilder strbld = new StringBuilder();

for (int i = 0; i < this.richTextBox1.Text.Length; i++)
{
   char c = this.richTextBox1.Text[i];

   if (c.ToString() != "\n")
      strbld.Append(c);
}

MessageBox.Show(strbld.ToString());
好吧,ChrisF是对的。怎么样:

string strRtf = richTextBox1.Rtf.Replace("\\par\r\n", " ");
strRtf = strRtf.Replace("\\line", " ");
richTextBox2.Rtf = strRtf;

: - |