【问题标题】:How to make a listbox item not duplicate itself to the next line of the listbox in C#如何使列表框项不复制到 C# 中列表框的下一行
【发布时间】:2017-02-12 22:08:13
【问题描述】:

所以我通过单击图像在列表框中添加一个项目。 如果该项目被多次单击或添加,它会将自身复制到列表框的下一行。我想要的是该项目有一个计数器来计算它被点击的实例数。

到目前为止,这是我的代码:

int ctr = 1;
 private void item_img1_Click(object sender, EventArgs e)
        {

            if (!orderList.Items.Contains(item1.Text))
            {
                orderList.Items.Add(item1.Text + ctr);
                ctr++;
            }

        } 

【问题讨论】:

  • 如果您想只允许添加 1 个项目(此图像类型),为什么不在成功添加第一个实例后简单地删除点击事件?

标签: c# winforms listbox


【解决方案1】:

请注意,您实际上并没有添加item1.Text;您正在添加item1.Text + ctr。这就是为什么您的 if 子句不会阻止您添加重复项的原因。

【讨论】:

    【解决方案2】:

    使用此代码:

    class ItemWrapper
    {
        public object item;
        public string text;
        public int ctr = 1;
        public override string ToString()
        {
            return text + " (" + ctr + ")";
        }
    }
    
    private void item_img1_Click(object sender, EventArgs e)
    {
        bool found = false;
        foreach (var itm in orderList.Items)
            if ((itm as ItemWrapper).text == item1.Text)
            {
                (itm as ItemWrapper).ctr++;
                found = true;
                break;
            }
        if (!found)
            orderList.Items.Add(new ItemWrapper() { item = item1, text = item1.Text, ctr = 1 });
    }
    

    ItemWrapper 是您的 item 对象的包装器,其中覆盖 ToString() 方法允许 listBox 将对象显示为您定义的格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多