Have in mind that this problem probably is the consequence of a beginners-mistake.
There are there 4 classes in my program relevant for this problem.
Main form: Declares and initiates the object currentRecipe (uses class recipe) and recipeMngr (uses class recipeManager) directly in the class. currentRecipe(Recipe) have a couple of fields that is collected from user input, the fields include the array ingredients[] that is collected from a property in another form that opens when a button is pressed. currentRecipe is used later when "add recipe button" is pressed and because it is used in both these methods the object currentRecipe needs to be initialized outside these methods as i understand it.
RecipeManager: Hold an array that stores the recipes. And method that that manages the adding of the recipe into the array. this method takes currentRecipe as a property from the main form.
Recipe: Holds the template for Recipe.
FormIngredients: collect ingredients from user and stores them in property.
However, the problem. When storing an recipe in the array in recipeManager the latest stored array just copies so all earlier assigned items in the list gets the new value. As an result
recipe[0] = Waffles
recipe[1] =
...
when adding a new it becomes
recipe[0] = pie
recipe[1] = pie ...
When it should become
recipe[0] = Waffles
recipe[1] = pie
...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeGUI();
}
private const int maxRecipe = 20;
private const int maxIngredients = 50;
private static Recipe currentRecipe = new Recipe(maxIngredients);
private static RecipeManager recipeMngr = new RecipeManager(maxRecipe);
private void btnAddIngredients_Click(object sender, EventArgs e)
{
FormIngredients FormI = new FormIngredients(currentRecipe);
var result = FormI.ShowDialog();//show ingredient form
if (result == DialogResult.OK) {
currentRecipe = FormI.recipe;
lblIngredAmount.Text = "Ingredients: " + currentRecipe.ingredientsAmounts().ToString();
}
}
private void AddRecipe(Recipe scurrentRecipe) {
scurrentRecipe.rName = tbxName.Text;
scurrentRecipe.rDescription = tbxDescription.Text;
scurrentRecipe.rCategory = (FoodCategories)cbxCategory.SelectedIndex;
bool valid = checkIfValid();
if (valid)
{
recipeMngr.Add(scurrentRecipe);
updateGUI();
SimpleInitializeGUI();
}
else
{
MessageBox.Show("Please fill all the fields (or add atleast one ingredient)", "Stop");
}
}
I've added the most important parts from main form, where is know the problem is from.
I want to add that the problem disappears when moving the initialization of currentRecipe into the "addRecipe click"-method. But this creates alot of new problems and the code is supposed to be structured like this.
I do not use any loop to fill the array.