Antonio Mercado
Antonio Mercado

Reputation: 55

How to make a listbox item not duplicate itself to the next line of the listbox in C#

so I am adding an item in a listbox by clicking an image. If the item gets clicked or added multiple times,it duplicates itself to the next line of the listbox. What I want is the item to have a counter that will count the number of instance it was clicked.

here's my code so far:

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++;
            }

        } 

Upvotes: 0

Views: 60

Answers (2)

Hossein Golshani
Hossein Golshani

Reputation: 1897

Use this code:

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 });
}

Where ItemWrapper is wrapper of your item object and overriding ToString() method in it allows listBox to display object as your defined format.

Upvotes: 0

adv12
adv12

Reputation: 8551

Note that you're not actually adding item1.Text; you're adding item1.Text + ctr. That's why your if clause isn't keeping you from adding duplicates.

Upvotes: 1

Related Questions