简体   繁体   English

如何在 Form1 中调用 Form2

[英]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.我正在做一个有 7 个表格的商店,表格 1 是商店的基础,带有图片框和一个说明我应该支付多少钱的文本框。 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".当我点击图片的框时,例如在 T 恤上,它会打开一个包含一些信息的新表单和一个按钮,上面写着“添加到购物车”。 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.基本上我想单击“添加到购物车”按钮,然后 Form2 关闭并返回到表单 1,并且在文本框中(显示我应该支付多少)显示值。

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:例如,假设您在Form1上公开了一个接受值并更新 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.然后,当单击“添加到购物车”按钮时,您可能希望从Form2调用该方法。 Something like:就像是:

form1Instance.UpdatePayAmount(someAmountValue);

So your Form2 code needs a reference to an instance of Form1 in a variable somewhere.所以你的Form2代码需要在某个地方的变量中引用一个Form1的实例。 Since Form2 now depends on Form1 , a sensible place to put that requirement would be in its constructor.由于Form2现在依赖于Form1 ,将这个要求放在它的构造函数中是一个明智的地方。 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.现在,当您创建Form2需要对Form1实例的引用,因此当单击按钮时,它可以调用该实例上的方法。 So when you create Form2 in your Form1 code you would supply that instance:因此,当您在Form1代码中创建Form2 ,您将提供该实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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