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?
Asked
Active
Viewed 4,579 times
0

Shog9
- 156,901
- 35
- 231
- 235

user1647667
- 1,269
- 4
- 14
- 26
2 Answers
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.
-
why there is error on textbox1.Text when I add the public string ModifyTextBoxValue? – user1647667 Nov 26 '12 at 02:14
-
@user1647667 What error are you getting, the above code works correctly – Mark Hall Nov 26 '12 at 02:19
-
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 Nov 26 '12 at 02:23
-
@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 – Mark Hall Nov 26 '12 at 02:31
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;

Community
- 1
- 1

Aurelius Anugrah Sugianto
- 327
- 2
- 3
- 11