简体   繁体   English

如何将存储在“属性”中的变量传递到另一个Windows窗体中?

[英]How do I pass variables stored in Properties into another windows form?

So I need to be able to pass a property(name) into another windows form. 因此,我需要能够将属性(名称)传递到另一个Windows窗体中。

In the first form, the user is prompted to key in their name, while in the second one, their name is shown. 在第一种形式中,提示用户键入其名称,而在第二种形式中,显示其名称。

My problem is that although the value keyed in in the first form is saved (I have a Message box to show me) when the new form runs, the value of the property is reset to the placeholder name from the constructor class. 我的问题是,尽管在新表单运行时保存了第一个表单中键入的值(我有一个消息框显示给我),但该属性的值从构造函数类重置为占位符名称。 Here are the codes(Form1 being the second form) 这是代码(Form1是第二种形式)

Both of them have initialised the reference to the contructor class at the start. 两者都在一开始就初始化了对构造器类的引用。

else if (select > 0 || txtName.Text != "")
{
    p.Name = txtName.Text; // Save Name as property                 
    MessageBox.Show("" + p.Name);
    this.Hide();
    Form1 form = new Form1();

    form.ShowDialog();

}

For Form1: 对于Form1:

private void Form1_Load(object sender, EventArgs e)
{
    setName();
    MessageBox.Show("" + p.Name);
    timer1.Start();
    label3.Text = "Player: " + p.Name;    
}

Create a property in Form1 to accept the name: Form1创建一个属性以接受名称:

public class Form1 : Form
{
    //other stuff

    public string Name {get;set;}
}

Then set that property when creating the form: 然后在创建表单时设置该属性:

else if (select > 0 || txtName.Text != "")
{
    this.Hide();
    Form1 form = new Form1();
    form.Name = txtName.Text;
    form.ShowDialog();
}

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

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