简体   繁体   中英

How to Display value of textbox in label in another form?

Hi I'm new to C# and I want to display the value of my textBox1 in form1 to my Label1 in form2. I tried using this:

private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = textBox1.Text;

        Form2 frm = new Form2();
        frm.Show();
        this.Hide();
    }

But it didn't work because it's in another form. Can someone tell me how to do it right?

In form1 write this code

private void button1_Click(object sender, EventArgs e)
{
        Form2 form = new Form2(TextBox1.Text);
        form.Show();
    }

In form2 write this

public Form2(string text)
    {
        InitializeComponent();
        label1.Text = text;
    }

Try to do this :

 // In Form1.cs.
private Form2 otherForm = new Form2();
private void GetOtherFormTextBox()
{
    textBox1.Text = otherForm.label1.Text;
}
private void button1_Click(object sender, EventArgs e)

    GetOtherFormTextBox();
}

Another option

In form1

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.LabelText = "My Text";
    from.ShowDialog();
}

In Form 2

private string labelText;
public string LabelText { get { return labelText; } set { labelText = value; } }
private void Form2_Load(object sender, EventArgs e)
{
    label.Text = LabelText;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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