I have a program in which the user inputs information into two separate text boxes and then clicks a button, at which time the program does some work and returns data to a third text box.
Then the user enters data into another textbox and clicks a second button. The program takes the text box return data from the first button click method along with the new input data, does some work and returns data to a mutli-line text box.
The problem I am having is that once the program leaves the first button click method, the return data disappears, so no data from the first button click method gets passed to the second button click method.
I am pretty sure it does this because the object is instantiated inside of the first button click method instead of being instantiated at the class level and therefore once the program leaves the method the object is gone. I attempted to instantiate the object at the class level but I cannot because I receive a “field initializer cannot reference the non-static field, method, or property” error.
I have looked at the MSDN specifications for this problem and understand what causes it, but the answer they give to fix it is to instantiate the object inside of the method. So I am right back to where I started from.
I am at a loss on what to do here. Here is my code with the object instantiated inside of the button click method:
private void btnOrderButton_Click(object sender, EventArgs e)
{
numberOfPizzas = int.Parse(this.txtNumberOfPizzaOrdered.Text);
numberOfCokes = int.Parse(this.txtNumberOfCokesOrdered.Text);
PizzaOrder orderObject = new PizzaOrder(numberOfPizzas, numberOfCokes);
this.txtAmountDue.Text = orderObject.TotalAmountDue.ToString("C");
}
private void btnPaymentButton_Click(object sender, EventArgs e)
{
amountDue = double.Parse(this.txtAmountDue.Text);
amountPaid = double.Parse(this.txtAmountPaid.Text);
Payment orderPaymentObject = new Payment(amountDue, amountPaid);
}
The data disappears because you’re creating a temporary object at the method’s scope, meaning it doesn’t exist outside the method.
To fix that declare the data member at the class level and use it like so:
Repeat the process for any other data object you need.