0

在 Windows 窗体上,我有 RichTextBox,其中包含一些文本,分几行。和表单上的一个按钮。

我想当我点击那个按钮时,将所有richtextbox的行加入一行,但不要松散文本样式(如字体系列、颜色等)

我不能用 Replace 来做到这一点,比如 \r\n,而不是用 Replace(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

4 回答 4

2

这将起作用:

        // 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;
        }
于 2009-10-28T14:13:28.030 回答
0

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

于 2009-10-28T09:56:23.537 回答
-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;

:-|

于 2009-10-28T14:07:18.513 回答
-1

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

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

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

于 2009-10-28T09:58:15.220 回答