2016-02-24 75 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()); 
    } 
} 

您可能必须根据需要重置计数器。