Reading values from another form

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

When you pull up a second form in your program,
how do you get the values from the form?

Form2 dataForm = new Form2();

dataForm.ShowDialog();
if (dataForm.DialogResult == DialogResult.OK)
{
// I want to get the textBox1 data from the form
}


Thanks.
 
In this case the best approach would be to expose what you want as public
properties on Form2 - i.e.

public string CustomerName {
get {return textBox1.Text;}
}

then you can access dataForm.CustomerName

For info, ShowDialog() [unlike Show()] doesn't Dispose() the form, so it
would be best to be "using" this - i.e.
using(Form2 dataForm = new Form2()) {
// do everything you want
}
// it is now disposed
Marc
 
Marc's solution most definitly works, I like to be a bit more complex
and make a private variable to hold the value and then a public
property to read the private variable. This way, when the user click
on OK on the second form, the second form can validate and make sure
everything is correct before loading the value into the variable and
exiting. If the user clicks on cancel, the value is never populated
and the first form, even if it tries to get the value, cannot.
 
Back
Top