I'm learning C# methods and I've created a boolean method CheckDuplication() to check if car registration plates that a user types into a textbox are already in the list. My AddNewCar() method adds a new car to the list so long as the registration plate isn't a duplicate (already in the list), or it is not left blank and it must be 6-8 characters in length. If it doesn't fail on the checks, it should go ahead and add the car to the list. However, if I type in a duplicate reg number, it correctly shows the error message for duplicate, but then goes ahead and adds the car anyway! The other checks correctly just display the error message and don't add the car. Sorry, I can't figure out why this isn't working correctly. Thank you.
private bool CheckDuplication()
{
string reg = regNumTextBox_.Text.ToUpper();
foreach (RentalCar car in rentalList_)
if (reg == car.RegPlateNum)
{
MessageBox.Show("This is a duplicate registration number.");
}
return false;
}
private void AddNewCar()
{
string reg = regNumTextBox_.Text.ToUpper();
bool trans = transmissionCheckBox_.Checked;
bool nav = navSystemCheckBox_.Checked;
if (CheckDuplication())
{
MessageBox.Show("This is a duplicate registration number.");
}
else if (regNumTextBox_.Text == "")
{
MessageBox.Show("You can't leave the registration box empty.");
}
else if (regNumTextBox_.Text.Length < 6 || regNumTextBox_.Text.Length > 8)
{
MessageBox.Show("You must type a registration plate between 6 and 8 letters and digits");
}
else
//if all of the checks are ok, go ahead and add the new car
{
// add new car
RentalCar car = new RentalCar(reg, trans, nav);
// Add the new car to the end of the list
rentalList_.Add(car);
// Clear and reset all input boxes
ResetInputBoxes();
}
}
Aucun commentaire:
Enregistrer un commentaire