2017-02-26 31 views
0

我正在處理一個非常簡單的訂單,它將通過標籤打印機進行打印。 我有一個richTextBox來顯示哪些項目已被添加和多少,但我不明白如何編輯文本框的「部分」是添加相同項目的多個項目。更新RichTextBox C的一部分#

我目前有2個按鈕,1個雞和1個鮭魚。

private void button1_Click(object sender, EventArgs e) 
    { 
     chickenCount++; 
     richTextBox1.Text = richTextBox1.Text + "\nChicken " + chickenCount + "x"; 
    } 

private void button3_Click(object sender, EventArgs e) 
    { 
     salmonCount++; 
     richTextBox1.Text = richTextBox1.Text + "\nSalmon " + salmonCount + "x"; 
    } 

所以我們說你加雞1條,然後1條鮭魚,之後,又添加了另一個雞。

這段代碼的輸出將是:

Chicken 1x 
Salmon 1x 
Chicken 2x 

現在我知道,這個代碼只是不斷的richTextBox

下一行添加文字,但我想要的輸出爲是:

Chicken 2x 
Salmon 1x 

但我真的不知道如何編輯的richTextBox

東西直列
+2

難道你不能重寫richtextbox的整個內容嗎? – rene

+0

??? a)你不想雞3x? b)爲什麼使用RichtTextBox? c)如果你想格式化,你永遠不要直接改變文本! d)你需要用你的數據保存一個列表或字典來做數學運算__before__創建文本e)你打算怎樣計劃prnt? RTB不會幫助你! – TaW

+1

您可以使用['ObservableCollection'](https://msdn.microsoft.com/en-us/library/ms668604(v = vs.110).aspx),並隨時更新「RichTextBox」(完全重寫它) –

回答

0

您可以使用SelectedText屬性和Select方法替換文本框上的一行。例如:

int line = 0; //The line that we want to replace is the first one 
string newstr = "Chicken x2"; //We want to replace the line with this string 
int charindex = this.GetFirstCharIndexFromLine(line); //Get the index of the first character of the line 
richTextBox1.Select(charindex, richTextBox1.Lines[line].Length); //Select the line 
richTextBox1.SelectedText = newstr; //Replace its text with the string 

如果你不知道哪一行要更換呢,遍歷數組Lines搜索的文本。