Reading values from another form

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.
 
M

Marc Gravell

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
 
C

Cartoper

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top