简体   繁体   中英

How to call Form2 in Form1

I'm doing a shop with 7 forms, the form 1 is the basic of the store with picture's Box and a textbox saying how much should I pay. When I click in the picture's box, for example in a T-shirt, it opens a new Form with some information and a button saying "add to cart". Basically I want to click on the button "add to cart" and then the Form2 closes and back's to form 1 and in the textbox (that shows how much should I pay) shows the value.

Forms are objects like any other, and you can pass references to them and call methods on them like any other.

For example, let's say you expose a method on Form1 which accepts the value and updates the UI:

public void UpdatePayAmount(double amount)
{
    // use the supplied value to update your text box
}

Then you would want to call that method from Form2 when clicking on the "Add to Cart" button. Something like:

form1Instance.UpdatePayAmount(someAmountValue);

So your Form2 code needs a reference to an instance of Form1 in a variable somewhere. Since Form2 now depends on Form1 , a sensible place to put that requirement would be in its constructor. Perhaps populating a private field:

private Form1 form1Instance;

public Form2(Form1 form1)
{
    form1Instance = form1;
}

Now Form2 requires a reference to an instance of Form1 when you create it, so it can call a method on that instance when the button is clicked. So when you create Form2 in your Form1 code you would supply that instance:

form2 = new Form2(this);
form2.Show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM