2016-02-24 76 views
2

所以我有一個按鈕,在這裏如果你點擊它,它增加了"Candy"listbox,我怎麼讓它如此,如果被添加具有相同名稱的另一個項目,而不是在一個新的生產線將它添加,更新第一行顯示x2,3,4等。是否有可能或將不得不作出另一個Listbox並匹配索引?我已經嘗試了以下另一個listbox和一個int變量。如何計算ListBox中的重複項並顯示旁邊重複項的數量?

private void btnCandy_Click(object sender, EventArgs e) 
    { 
     lstProducts.Items.Add("Candy"); 
     foreach (var item in lstProducts.Items) 
     { 
      if (item.ToString() == "Candy") 
      { 
       ++Productcount; 
       lstQuantity.Items.Add(Productcount); 
       if (Productcount > 1) 
       { 
        lstQuantity.Items.Insert(lstProducts.Items.IndexOf("Candy"), Productcount); 
       } 
      } 
     } 
    } 
+0

什麼具有u迄今所做?問題不是很清楚明白 –

+0

能否請您包括,增加了「糖果」到一個列表框 –

+0

我有一個按鈕的片段,和一個列表框。當我點擊按鈕時,它將字符串「Candy」添加到列表框中。 –

回答

3
using System.Text.RegularExpressions; 

用途:

private void btnCandy_Click(object sender, EventArgs e) 
{ 
    string query = "Candy"; 
    bool isExist = false; 
    for (int i = 0; i < lstProducts.Items.Count; i++) 
    { 
     var s = lstProducts.Items[i].ToString(); 
     if (s.StartsWith(query)) 
     { 
      if (s == query) 
      { 
       lstProducts.Items[i] = query + "x2"; 
       isExist = true; 
       break; 
      } 
      else 
      { 
       // Escape your plain text before use with regex 
       var pattern = Regex.Escape(query); 
       // Check if s has this formnat: queryx2, queryx3, queryx4, ... 
       Match m = Regex.Match(s, "^" + pattern + @"x(\d+)$"); 
       if (m.Success) 
       { 
        lstProducts.Items[i] = query + "x" + (Int32.Parse(m.Groups[1].Value) + 1); 
        isExist = true; 
        break; 
       } 
      } 
     } 
    } 
    if (!isExist) lstProducts.Items.Add(query); 
} 

注:

  • \d意味着任何數字(0 - 9)
+0

這是相當接近,如果存在,它增加了X2但X2後,它會創建一個新行和重複 –

+0

哇,這完美地工作。我從來沒有真正使用過正則表達式,但這是一些非常好的代碼。謝謝。 –

+0

我已經給你選擇的答案,我已經給你答案了,我已經給你答案了。 –

0

我想嘗試遍歷列表框項目,如果我找到「糖果」,然後採取索引和更新標題。

private void btnCandy_Click(object sender, EventArgs e) 
{ 
    bool found = false; 
    foreach (var item in lstProducts.Items) 
    { 
     if (item.ToString().StartsWith("Candy")) 
     { 
      // update item title 
      found = true; 
      break; // no need to continue 
     } 
    } 
    if(!found) 
    { 
     lstProducts.Items.Add("Candy"); 
    } 
} 

這樣你是不是要添加重複

0

下面是一些僞代碼,以幫助您。將此添加到您的按鈕單擊事件中:

int i = 0; 
foreach (string item in listbox1.Items) 
{ 
    If (item == textbox1.text) //textbox1.text contains the string such as 'candy' 
    { 
     i++; 
     listbox1.Items.Remove(item); 
     listbox1.Items.Add(textbox1.text + " " + i.ToString()); 
    } 
} 

您可能必須根據需要重置計數器。