将变量传递给另一种forms

我正在用c#开发一个Windows应用程序。 我使用了三个十进制变量: counternarrowbroad ,它们根据某些计算存储不同的值。

单击按钮时,将显示一个消息框,显示这三个十进制值,然后应用程序退出..

现在我想添加另一个具有三个标签的表单,其中需要显示这些变量值。 请解释一下,如何在下一个表单中传递这些变量以在单个标签中显示?

创建一个新表单…

 public class CalculationResultForm : Form { public CalculationResultForm(){} public decimal Counter { set { labelCounter.Text = value.ToString(); } } public decimal Broad { set { labelBroad.Text = value.ToString(); } } public decimal Narrow { set { labelNarrow.Text = value.ToString(); } } private void OkButton_Click(object sender, EventArgs e) { // This will close the form (same as clicking ok on the message box) DialogResult = DialogResult.OK; } } 

然后在现有的表单按钮单击处理程序…

 private void MyButton_Click(object sender, EventArgs e) { CalculationResultForm resultForm = new CalculationResultForm(); resultForm.Counter = _counter; resultForm.Narrow = _narrow; resultForm.Broad = _broad; resultForm .ShowDialog(); Application.Exit(); } 

一种方法是在第二种forms中创建一个新的构造函数。 你可以使用第二种forms的那些值。

 public Form2(decimal x, decimal y, decimal z):this() { this.TextBox1.Text = Convert.ToString(x); this.Label1.Text = Convert.ToString(y); etc... }; 

从主要forms

 Form2 frm2 = new Form2(x,y,z); frm2.Show(); 

最简单的方法是添加一个新方法,让我们称之为ShowWithDetails:

  public void ShowWithDetails(double Counter, double Narrow, double Broad) { CounterLabel.Text = Counter.ToString(); NarrowLabel.Text = Narrow.ToString(); BroadLabel.Text = Broad.ToString(); ShowDialog(); } 

一种简单的方法是使用属性。 您要将值传递给的表单只是另一个类。

将这样的内容添加到第二种forms:

 public int counter {get; set;} 

那么从第一种forms开始你就会做一些事情

 Form2 form2 = new Form2(); form2.counter = 1; form2.ShowDialog(); 

或类似的规定。

有一篇博客文章描述了如何在不使用ShowDialog()的情况下执行此操作 。