Check for duplicates in a ListBox

What I would like to achieve is this: every time I add student, it should check ListBoxif there is a duplicate entry inside it. If so, it should show MessageBoxand not add the item to 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 is not working correctly. Input comes from several TextBoxesin the form that is added to List<Students>and ListBox.

+4
source share
1 answer

, , Equals Student. Equals , Equals object . , , , false object.Equals, Contains false.

+4

Source: https://habr.com/ru/post/1621159/


All Articles