I have a program where the user can add products to the system, and then search them by the product name. Everything is working fine, except at the moment is able to enter two products with the same name. I need the program to not allow this.
I have a method assigned to the 'Add' button, which saves the product name, customer name and firmware location to a text file. Here is that method:
private void button_Click(object sender, RoutedEventArgs e)
{
bool found = false;
string searchTerm = productNameTextBox.Text.ToUpper();
if ((productNameTextBox.Text == "") || (customerNameTextBox.Text == "") || (firmwareLocationTextBox.Text == ""))
{
MessageBox.Show("Please fill in all the text boxes");
}
else if (Contains(searchTerm) == true)
{
MessageBox.Show("Product already added");
}
else
{
string inputCustomerName = customerNameTextBox.Text.ToUpper();
string inputProductName = productNameTextBox.Text.ToUpper();
string inputFirmwareLocation = firmwareLocationTextBox.Text;
try
{
Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation);
newProduct.Save("Products.txt");
File.AppendAllText("ProductNames.txt", inputProductName + Environment.NewLine);
MessageBox.Show("Product added");
emptyTheTextBoxes();
}
catch
{
MessageBox.Show("Product could not be added");
}
}
}
I have also made a method which will search a text file to see if the users product name has already been stored, and then return a Boolean. This is the method:
public bool Contains (string searchTerm)
{
string line;
bool found = false;
System.IO.StreamReader file = new System.IO.StreamReader("ProductNames.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(searchTerm))
{
found = true;
break;
}
}
if (found == true)
{
return true;
}
else
{
return false;
}
file.Close();
}
When I try to save the input, a message box appears saying "Product could not be added". However, if I comment out the else if statement which calls the method, it works fine.
I thought it may be because I open the file when the method is called, and maybe it wasn't closing properly. So I added the 'file.Close()' and it hasn't made a difference. I feel like I've just made a silly mistake somewhere, but its been bugging me for hours! Definitely appreciate a fresh pair of eyes!
Thanks Lucy