Silvia Stoyanova
Silvia Stoyanova

Reputation: 281

Check a list against user input?

I am trying to check whether a list contains a value, which is user input. The user input is in textbox named txtId and it is an int. If the userId is already existing in the list it has to throw an exception from my class AlreadyExistingIdException.

When I do it that way I get an error saying that Contains() has some invalid arguments:

 private void btnAddClass_Click(object sender, EventArgs e)
 {
        Classes newClass;
         // Open new form to input  data
            AddNewClass add_form = new AddNewClass();
            if (add_form.ShowDialog() == DialogResult.OK)
            {
                newClass = new Classes();
                // Get new  data from second form
                newClass = add_form.ExtractData();
               //check if id already exists in the list
                **if (l.fitnessClasses.Contains(newClass.Id))
                {
                    //throw an exception
                }
                else
                {**
                    // Add the new class to  file
                    l.AddClass(newClass);
                    lstClasses.Items.Clear();
                    //sort the list by ID
                    l.fitnessClasses.Sort((a, b) => a.Id.CompareTo(b.Id));

                    foreach (Classes cl in l.fitnessClasses)
                    {
                        lstClasses.Items.Add(cl);  //add  to list box
                    }


                    // Display new  
                    MessageBox.Show(newClass.Display());
                }
            }     
    }

Upvotes: 2

Views: 1719

Answers (2)

Orkun
Orkun

Reputation: 7228

Either override Equals and GetHashCode methods in the Classes (because your class needs to know how to compare instances, see msdn for how to) then you can call:

l.fitnessClasses.Contains(newClass); 

or use Linq

l.fitnessClasses.Contains(p=> p.Id == newClass.Id)

Upvotes: 2

Tod
Tod

Reputation: 8232

If you are familiar with linq you can do something like

if ( l.fitnessClasses.Any(x=> x.Id == newClass.ID)) {...}

Upvotes: 1

Related Questions