简体   繁体   中英

Accessing a textbox value from form1 in form2

I have a textbox on form1.
What I want to do is to get the value of the textbox from form1 into form2.
How can I do this?

What I did was create a new project and add a second form then added a textbox to both forms, with a button on Form1 to push the value of its text box to Form2.

To achieve this, create a Property on Form2 and set it from Form1. Like this:

Form1

public partial class Form1 : Form
{
    Form2 frm2;
    public Form1()
    {
        InitializeComponent();
        frm2 = new Form2();
        frm2.Show(this);
    }

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

Form2

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

    public string ModifyTextBoxValue
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }
}

Done this way, the same property can also be used to pull data from Form2 if desired.

you could use the .Tag property (look at my question here the simple way to do it is like this: add another textBox in form2

do this in the form1. this code will store the texBox.text in form1

try
{
    private void change_Click(object sender, EventArgs e)
    {
         form1 frm1 = new form();
         frm1.Tag = this.textBox1.text;
         frm1.ShowDialog();
    }
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

then write this when you load your form2. this code will replace texBox2 value with the value of texBox1

string myText = (string)this.Tag;
   this.textBox2.text = myText;

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