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] + ")");
}
任何幫助表示讚賞每個項目數量的軌道!在此先感謝
這就是我下車的MSDN頁面的代碼。行號只是用於測試,它似乎適用於此,因爲它確實爲該項目提供了行號。如果我想要用戶點擊的項目的索引,我將如何更改while循環? – Donovan
@Donovan:我更新了答案,以解釋循環在做什麼,爲什麼它被打破,以及如何解決它。 –
希望我不應該確定有什麼被發現,因爲如果它不在那裏它被添加進去。我想我明白你在做什麼,當我嘗試它時,它給了錯誤「索引和計數必須指向一個位置在字符串內「。我試圖改變刪除的字符數量,它仍然給出了同樣的錯誤。我會用新代碼更新我的帖子.. – Donovan