Hashey100
Hashey100

Reputation: 984

How to get a list box to disallow duplicate items?

Bassicly im creating a program that reads information from an xml file into a lisbox and allows the user to transfer items in the list box to another listBox.

But i want to some how disallow multiple items from being imported from one listBox to the other. I thought i can somehow do an experession to check if the String already Exists in the listBox.

The reason i want to do this is because the user can click x amount of times in order to import items and it's unproffesional.

Any Help would be appreciated thank you.

private void button1_Click(object sender, EventArgs e)
{
    if (!listBox.Items.Exists) // Random Idea which doesnt work
    {
        listBox2.Items.Add(listBox1.Items[listBox1.SelectedIndex]);
    }
}

Upvotes: 0

Views: 4953

Answers (2)

Faraday
Faraday

Reputation: 2954

This should do it for you...

private void button1_Click(object sender, EventArgs e)
    {
        if (!ListBox.Items.Contains(listBox1.SelectedItem)) // Random Idea which doesnt work
        {
        listBox2.Items.Add(listBox1.SelectedItem);
        }

    }

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124790

private void button1_Click(object sender, EventArgs e)
{
    if (!listBox.Items.Exists) // Random Idea which doesnt work
    {
    listBox2.Items.Add(listBox1.Items[listBox1.SelectedIndex]);
    }

}

That will work actually, but you need to use the Contains method. However, you may be missing one crucial point.

What type of items are you using to populate your ListBox? Exists will call .Equals which, by default, uses reference equality. So, if you need to filter based on value, you need to override .Equals for your type and change the semantics.

For example:

class Foo 
{ 
    public string Name { get; set; }
    public Foo(string name)
    {
        Name = name;
    }
}

class Program
{
    static void Main( string[] args )
    {
        var x = new Foo("ed");
        var y = new Foo("ed");
        Console.WriteLine(x.Equals(y));  // prints "False"
    }       
}

However, if we override .Equals to provide value type semantics...

class Foo 
{ 
    public string Name { get; set; }
    public Foo(string name)
    {
        Name = name;
    }

    public override bool Equals(object obj)
    {
        // error and type checking go here!
        return ((Foo)obj).Name == this.Name;
    }

    // should override GetHashCode as well
}

class Program
{
    static void Main( string[] args )
    {
        var x = new Foo("ed");
        var y = new Foo("ed");
        Console.WriteLine(x.Equals(y));  // prints "True"
        Console.Read();
    }       
}

And now your call to if(!listBox.Items.Contains(item)) will work as you intended it to. However, if you wish it to continue working you will need to add the item to both listboxes, not just listBox2.

Upvotes: 3

Related Questions