2013-07-08 39 views
0

我正在C#中開發一個文本編輯器,並且我正在嘗試進行一次行計數。Richtextbox行數

private void updateNumberLabel() 
    { 
     Point pos = new Point(0, 0); 
     int firstIndex = Document.GetCharIndexFromPosition(pos); 
     int firstLine = Document.GetLineFromCharIndex(firstIndex); 

     pos.X = ClientRectangle.Width; 
     pos.Y = ClientRectangle.Height; 

     int lastIndex = Document.GetCharIndexFromPosition(pos); 
     int lastLine = Document.GetLineFromCharIndex(lastIndex); 

     int actualLine = Document.GetLineFromCharIndex(actualPos); 
     pos = Document.GetPositionFromCharIndex(lastIndex); 

     if (lastLine != actualLine) 
     { 
      numberLabel.Text = ""; 
      for (int i = firstLine; i <= lastLine + 1; i++) 
      { 
       numberLabel.Text += i + 1 + "\n"; 
      } 
     } 
    } 

它工作正常,雖然你寫它們添加的行數,但如果你刪除一個,如果刪除或添加更多的行只會更新。

我想讓它瞬間。如果刪除一個,計數應立即減少。

+1

'richTextBox.Lines.Count()'有什麼問題? – derape

回答

3

這也許是太容易了,但什麼有關:

private void richTextBox1_TextChanged(object sender, EventArgs e) 
{ 
    var lineCount = richTextBox.Lines.Count(); 
    numberLabel.Text = lineCount.ToString(); 
} 

請務必將其分配給TextChanged事件。

如果這不是您所需要的,請添加更多信息,試圖實現。

+0

我試過了: numberLabel.Text + = Document.Lines.Count()。ToString()+「\ n」; 但它會在每次文字改變時將行添加到標籤 – Los799

+0

@ Los799您想顯示當前正在使用的行嗎?所以就這樣做:'numberLabel.Text = Document.Lines.Count()。ToString();' – derape

0

爲什麼不嘗試與默認的富文本框進行對戰,爲什麼不嘗試製作自己的控件,以便完全控制文本格式?

畢竟,如果您正在開發自己的文本編輯器,那麼將文本存儲和管理的方式對開發人員來說是有意義的,而不是試圖與專爲目的略有不同。

+0

我是C#的新手,如果我不知道如何計算行數,我怎麼能讓自己的控制?謝謝! – Los799

+0

在這種情況下,我正在做一些我很少做的事情,並且嘗試使用Romano的Environment.NewLine解決方案。註釋行以大寫字母L開始。 – Pharap

0

Los799

對不起,回答是「有點」晚了,我剛纔看到這個問題。 但是,如果問題仍然矗立,這裏有一個簡單的方法來計算行,只是使用foreach循環:

int CountOfLines = 1;//1 because min 1 line is always in a text of a control, that has a Text property 
foreach (char c in YourText) 
      { 
       if (c == '\r' | c == '\n')//these are all equal the ENTER key 
       { 
        CountOfLines++; 
       } 
      } 

您還可以使用的foreach來計算字符數爲好,但用foreach你可以選擇人物,你不希望被計入字符數。例如:

int CountOfCharacters = 0;//0 because by default there are no characters in a textbox or label. 
foreach (char c in YourText) 
      { 
       if (c != '\t' & c != '\n' & c != '\r')//in this example I want to count only the characters that are not an ENTER or a TAB. 
       { 
        CountOfCharacters++; 
       } 
      } 

希望這可以幫助您和所有其他人閱讀本文,即使它有點遲到的答案。 :)

0

我真的很晚,但Lines是一個字符串數組。只需獲得長度。

richTexBox.Lines.Length.ToString();