0

So I need to be able to pass a property(name) into another windows form.

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)

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:

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

1 Answers1

0

Create a property in Form1 to accept the name:

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();
}
Servy
  • 202,030
  • 26
  • 332
  • 449