简体   繁体   English

将变量传递为另一种形式

[英]passing variables into another form

I am developing a windows app in c#. 我正在用C#开发Windows应用程序。 I have used three decimal variables: counter , narrow , and broad which store different values based on some calculations. 我使用了三个十进制变量: counternarrowbroad ,它们根据一些计算存储不同的值。

On clicking a button, a message box is displayed showing these three decimal values and then the application exits.. 单击按钮时,将显示一个消息框,显示这三个十进制值,然后退出应用程序。

Now I want to add another form having three labels in which these variable values needs to be shown. 现在,我想添加另一个具有三个标签的表格,其中需要显示这些变量值。 Please explain, how can I pass those variables in the next form to display in individual labels? 请说明,如何在下一个表格中传递这些变量以显示在各个标签中?

One method is to create a new constructor in the 2nd form. 一种方法是创建第二种形式的新构造函数。 THen you can use those values from the 2nd form. 然后,您可以使用第二种形式的值。

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

From main form 从主要形式

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

The easiest way is to probably add a new method, lets call it ShowWithDetails: 最简单的方法是添加一个新方法,将其命名为ShowWithDetails:

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

        ShowDialog();
    }

Create a new Form... 创建一个新表格...

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;
    }
}

Then within your existing form button click handler... 然后在现有表单按钮中单击处理程序...

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();
}

An easy way is to use properties. 一种简单的方法是使用属性。 The form you want to pass the values to is just another class. 您想要将值传递给的表单只是另一个类。

add something like this to the second form: 在第二种形式中添加以下内容:

public int counter {get; set;}

then from the first form you'd do something along the lines of 然后从第一种形式开始,您将按照

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

or something along those lines. 或类似的规定。

有一篇博客文章描述了如何不使用ShowDialog()来执行此操作

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

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