Form TextBox values to Form2 TextBox values

[亡魂溺海] 提交于 2020-01-06 07:53:08

问题


Basically when a user enters data into a textfield on Form2, I want that data to be stored into a variable then when users selects the button enter, Form2 will hide and Form1 will appear. I then want Form1 to display the data entered in the textfield from Form2 in a new textfield.

This is my attempt, but it doesn't work

On Form 2...

public string Player1 {get; set;}

private void pvpPlay_Click(object sender, EventArgs e)
    {

        Player1 = txtPlayer1.Text;
        Form1 op = new Form1();
        op.Show();
        this.Hide();

    }

Then on Form1 to call this I put...

Form2 f = new Form2();
txtTest.Text = f.Player1;

But it doesn't work. Hopefully someone knows the answer.


回答1:


I would prefer the using of a simple Callback function like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public String SomeProperty { get; set; }

    private void OpenFormButton_Click(object sender, EventArgs e)
    {
        var secondForm = new Form2()
        {
            GetSomeProperty = () => { return SomeProperty ;};
        };
        this.Hide(); //The best way to hide!
        secondForm.Show();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        SomeProperty = "HELLO WORLD";
    }
}



public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public Func<string> GetSomeProperty
    {
        get;
        set;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        MessageBox.Show(GetSomeProperty.Invoke());
    }
}

Everytime you call GetSomeProperty.Invoke(); the Func will call the get accessor and return it from the first Form




回答2:


What you can do is overload the Form1 constructor.

public Form1(string s)
{  
    txtTest.Text=s;
}  

When calling from Form2

Form1 op = new Form1(Player1);


来源:https://stackoverflow.com/questions/14425713/form-textbox-values-to-form2-textbox-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!