Home > Back-end >  How do I check if my list box already contains the same entry before adding the same new one?
How do I check if my list box already contains the same entry before adding the same new one?

Time:12-20

I have tried to make a simple C# Windows Forms Application .NET Framework, where I have a class(string Name, string LastName, string Classroom, string DateDay) with three textbox entries and one date time picker entry. All of these entries get saved into a list and a list box. I need to add onto my if statement to check with for each, if the entry I am trying to put into the list/list box is already in the list box. If the entry is duplicate it will give a message box error, if it is not duplicate it will add it using the continuation of the if statement.

Here's my attempt at the duplication check:

private void btnAdding_Click(object sender, EventArgs e)
{
    if (txtName.Text != "" && txtLastName.Text != "" && txtClassroom.Text != "" )
    {
        if (ListBox.Items.Cast<string>().Contains(ListBox.Items.ToString()))
        {
            MessageBox.Show("This entry already exists.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else { 
        List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy")));
        RefreshCheck();
        }
    }
    else
    {
        MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

public void RefreshCheck()
        {
            ListBox.Items.Clear();
            for (int i = 0; i < seznam.Count(); i  )
            {
                ListBox.Items.Add(List[i].StudentAdd());
                this.txtName.Clear();
                this.txtLastName.Clear();
                this.txtClassroom.Clear();
                this.dateDay.Value = DateTime.Today;
                this.tabStudent.SelectedTab = this.tabCheck;
            }
        }

Here's my original code without the duplication check (just the if statement):

private void btnAdding_Click(object sender, EventArgs e)
{
    if (txtName.Text != "" && txtLastName.Text != "" && txtClassroom.Text != "" )
    {
        List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy")));
        RefreshCheck();
    }
    else
    {
        MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

public void RefreshCheck()
        {
            ListBox.Items.Clear();
            for (int i = 0; i < List.Count(); i  )
            {
                ListBox.Items.Add(List[i].StudentAdd());
                this.txtName.Clear();
                this.txtLastName.Clear();
                this.txtClassroom.Clear();
                this.dateDay.Value = DateTime.Today;
                this.tabStudent.SelectedTab = this.tabCheck;
            }
        }

I don't know how to setup the for each loop to check the list box / list entries. Please do help if you know how.

Here is the code on how I add into the list box:

List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy")));

Here is the way the class returns the value that gets added into the list box:

public string StudentAdd()
    {
        return $"{this.Name} {this.LastName} | {this.Clasroom} | {this.DateOfLeave}";
    }

Edited: changed OsveziPregledDijaka() -> RefreshCheck, added RefreshCheck function to code.

CodePudding user response:

You can use LINQ expression to see if the item is exists or not.

if(ListBox.Items.Any(i=>i.Name == txtName.Text && i.LastName == txtLastName.Text && i.ClassRoom == txtClassRoom.Text)
{
   //Show MessageBox
}

CodePudding user response:

You can override the Equals operator in the Student class, then use the Contains method to check the list.

public override bool Equals(object obj)
{
    if (obj == null || !(obj is Student student))
    {
        return false;
    }
    return Name == student.Name && LastName == student.LastName && Classroom == student.Classroom && DateDay == student.DateDay;
}

Then to check the item:

if (!ListBox.Items.Contains(student))
{
    ListBox.Items.Add(student);
}
else
{
    MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

CodePudding user response:

You need to search into the strings displayed by the listbox. But the code above uses ListBox.Items.ToString() and this will be just the ListBox class name not the individual strings displayed by the ListBox.

So, assuming that your listbox shows the info about the studend using firstname, lastname and classroom, you need to build a string like the one displayed by the items collection

 string searchFor = $"{txtName.Text} {txtLastName.Text} {txtClassRoom.Text}";

and with that string search the items collection (no need to call Cast())

 if (boxListBox.Items.Contains(searchFor))
    ....
 else
    ....

Here the complete event click handler rewritten

private void btnAdding_Click(object sender, EventArgs e)
{
    if (txtName.Text != "" && txtLastName.Text != "" && txtClassroom.Text != "" )
    {
        string searchFor = $"{txtName.Text} {txtLastName.Text} {txtClassRoom.Text}";
        if (boxListBox.Items.Contains(searchFor))
        {
            MessageBox.Show("This entry already exists.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else 
        { 
            List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy")));
            RefreshCheck();
        }
    }
    else
    {
        MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
  • Related