2011-11-29 19 views
1

因此,我試圖在Visual Studio 2010中的一個富文本框中替換一行。對於一個項目,我製作了一個菜單系統,當選擇了一個項目時,我需要更新顯示該項目編號的文本框。我不知道項目在列表中的具體位置,並且可能有多個項目顯示相同的編號,因此我無法使用.replace方法。我可以得到該項目所在的行號,但是當我嘗試使用索引查找行號時,出現錯誤,提示「StartIndex不能小於零」。下面的代碼我到目前爲止:從c#中的富文本框中取代一行#

//保持

int[] mainItems = new int[10]; 

    //function for menu item buttons 
    private void MenuButtonClick(object sender, EventArgs e) 
    { 
     int index = 0; 
     Button btn = (Button)sender; 
     string s = btn.Name.ToString(); 
     //if item doesnt already exist on order 
     if (!textBoxItems.Text.Contains(s)) 
     { 
      textBoxItems.Text += "\r\n• " + s; 
      //track num of each item 
      switch (s) 
      { 
       case "Tiramisu": mainItems[0]++; 
        break; 
       case "Lazania": mainItems[1]++; 
        break; 

      } 
      textBoxCount.Text += "\r\n(1)"; 
     } 
     else 
     { 
      int itemID = 0; 
      switch (s) 
      { 
       case "Tiramisu": mainItems[0]++; 
        itemID = 0; 
        break; 
       case "Lazania": mainItems[1]++; 
        itemID = 1; 
        break; 

      } 

      int lastIndex = 0; 
      //get line number of item 
      do 
      { 
       index = textBoxItems.Find(s, index + 1, RichTextBoxFinds.MatchCase); 
       if (index != -1) 
       { 
        lastIndex = index; 
       } 
      } while ((index != -1)); 
      //int lineNum = textBoxItems.GetLineFromCharIndex(index); 
      //MessageBox.Show("" + lineNum); 

      textBoxCount.Text.Remove(lastIndex, 2); 
      textBoxCount.Text.Insert(lastIndex, "(" + mainItems[itemID] + ")"); 

     } 

任何幫助表示讚賞每個項目數量的軌道!在此先感謝

回答

0

的問題是,你循環,直到指數== -1

while ((index != -1)); 

然後立即使用該索引

int lineNum = textBoxItems.GetLineFromCharIndex(index); 

我不知道的而什麼邏輯循環是,但乍一看,如果索引== -1,你可能想分手。或者跟蹤循環之外的最後一個非負數索引。

更新

要找到用戶只需點擊該項目,則需要改變循環記錄的最後一個索引,是不是-1。 while循環的目的是查找s的最後一次出現,但是必須將最後一個有效的出現記錄在單獨的變量中(以下代碼中的lastIndex)。您也必須測試循環完成後實際發現的內容。

這是我將如何實現這個邏輯:

 int lastIndex = -1; 

     //get line number of item 
     do 
     { 
      index = textBoxItems.Find(s, index + 1, RichTextBoxFinds.MatchCase); 
      if (index != -1) { 
       lastIndex = index; 
      } 
     } while ((index != -1)); 
     if (lastIndex !+ -1) { 
      int lineNum = textBoxItems.GetLineFromCharIndex(lastIndex); 
      //messageBox.Show(""+lineNum); 
      textBoxCount.Text.Remove(lastIndex, 3); 
      textBoxCount.Text.Insert(lastIndex, "(" + mainItems[itemID] + ")"); 
     } 
+0

這就是我下車的MSDN頁面的代碼。行號只是用於測試,它似乎適用於此,因爲它確實爲該項目提供了行號。如果我想要用戶點擊的項目的索引,我將如何更改while循環? – Donovan

+0

@Donovan:我更新了答案,以解釋循環在做什麼,爲什麼它被打破,以及如何解決它。 –

+0

希望我不應該確定有什麼被發現,因爲如果它不在那裏它被添加進去。我想我明白你在做什麼,當我嘗試它時,它給了錯誤「索引和計數必須指向一個位置在字符串內「。我試圖改變刪除的字符數量,它仍然給出了同樣的錯誤。我會用新代碼更新我的帖子.. – Donovan