0

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?

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

why there is error on textbox1.Text when I add the public string ModifyTextBoxValue?
@user1647667 What error are you getting, the above code works correctly
textBox1.Text does not exist in the current context. I just add textbox on the form2 that contains the same property name for the textbox. and same textbox property name in form1 @Mark Hall
@user1647667 Make sure you use the Property as written with the name of your TextBox in place of the TextBox that I used(TextBox1). All I did was create a new project and add a second form then added a textbox to both of them. What is the names of your Form1 and Form2 textbox, I will alter code to use them
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.