I have a C# problem I've been struggling with for a week now. I can't figure it out. I've made a sample application to demonstrate my problem: how do I pass data between forms? I've read tons of posts/articles etc. about doing this, but I cant make it work. The application I'm writing has a bunch of forms, so when I'm done with one, I'd like to close it to free resources. On the close button event on these forms, I'd like to update variables I've declared but not displayed in the main form class. (I'd really like to send back an array of variables from these forms I think - wow, that sounds daunting for me). Anyway, I can't seem to make it work. Here's my example:
Form1 code:
Form2 code:
When I click on the button in Form1 to MessageBox display the values I've typed into the textBoxes on forms 1 and 2, the Form1 textBox1 value is correct, but the Form2 textBox1 and 2 values (f2TB1 and f2TB2) are null. Why won't this work? Arg!!
Is there a better way to pass the values? Maybe make invisible textBox controls on Form1 and update them when I close Form2 - seems cheesy?
Thanks in advance for any help.
Form1 code:
Code:
public partial class Form1 : Form { private string f2TB1; private string f2TB2; public Form1() { InitializeComponent(); } public string frm2TextBox1 { set { f2TB1 = value; } } public string frm2TextBox2 { set { f2TB2 = value; } } private void button1_Click(object sender, EventArgs e) { Form2 newFormTwo = new Form2(); newFormTwo.ShowDialog(); } private void button2_Click(object sender, EventArgs e) //display values { string prompt = string.Format("Form1:{0}, Form2: {1}, {2}", textBox1.Text, f2TB1, f2TB2); MessageBox.Show(prompt); } }
Code:
public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form1 frm1 = new Form1(); //This works to create a new Form1 //and keep the old text I typed into its // textBox1 intact after I close Form2 //?why would it since I created a new Form1 frm1.frm2TextBox1 = textBox1.Text; frm1.frm2TextBox2 = textBox2.Text; this.Close(); } }
Is there a better way to pass the values? Maybe make invisible textBox controls on Form1 and update them when I close Form2 - seems cheesy?
Thanks in advance for any help.
Comment