user5650190
user5650190

Reputation:

Check for duplicates in ListBox

What I would like to achieve is as following: every time I add a student it should check the ListBox if there's a duplicate entry inside. If this is the case it should show a MessageBox and prevent adding the item to the ListBox.

This is my code at the moment:

private void buttonAdd_Click(object sender, EventArgs e)
{
       Student student = GetStudent();
       Repository.AddStudent(student);
       if (listBoxStudents.Items.Contains(student))
       {
            MessageBox.Show("This student already exists!");
       }
       else
       {
            listBoxStudents.Items.Add(student);
            ClearandFocus();
       }
}

I wonder why my code doesn't work correctly, The input comes from several TextBoxes in a form that gets added to a List<Students> and ListBox.

Upvotes: 4

Views: 99

Answers (1)

adv12
adv12

Reputation: 8551

This is probably happening because you haven't properly overridden the Equals method in your Student class. When you don't override Equals based on the class data, the default Equals method from the object class gets run, and that simply compares object references. So you're comparing two identical but distinct objects, which results in a value of false from object.Equals, which causes the Contains method to return false.

Upvotes: 3

Related Questions