2009-10-28 30 views
0

,我有RichTextBox,有幾行文字。和一個窗體上的一個按鈕。在Windows窗體上連接線

我wolud就像我那個按鈕點擊,加入行的所有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 

(和「一行三」是紅色的,因爲它以前)。

當我嘗試與

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

...我得到:

line 1 
line 2 
line 34 

「第2行」 爲紅色。

我該怎麼做才能解決這個問題?

+1

對不起,你的問題是不是很很清楚。當你做Replace時會發生什麼?你能包括一個'之前'和'之後'的例子嗎? – Benjol 2009-10-28 09:56:49

回答

-1

我敢打賭,你只是在文本字符串調用替換,你需要做的是這樣的:

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

這裏的關鍵是你需要將函數的結果賦給富文本框的文本,否則什麼都不會發生。看,字符串是不可變的並且每當你對其中一個執行操作時,你必須把操作的結果賦值給某個東西(即使原來的變量也能工作),否則什麼都不會發生。

+0

這裏你會失去格式。 – 2009-10-28 14:59:51

-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()); 

OK,ChrisF是正確的。這個怎麼樣:

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

: - |

+1

這將只是連接文本,並刪除格式 – ChrisF 2009-10-28 14:09:56

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; 
     } 
+0

如果這被證明是答案,你能標記它嗎? – 2009-11-07 18:50:31