I have two Windows Forms (MyApp, Generator), and I need to call Generator from MyApp
Form gen = new Generator();
gen.Show();
string result = gen.IDontKnowWhatToDoHere();
My Generator.cs Form has three TextBox and a Button Ok, so when the user type some text in the three TextBoxes an click Ok I want to get the the Text typed in those three TextBoxes.
Do you have any ideas how I can achieve this.
Thanks.
Although if you're not doing anything but returning from the form when you click the button, you could just set the DialogResult property on Form2. button1 in the form designer, and you wouldn't need an event handler in Form2 at all.
I generally use this pattern:
TResult result = Generator.AskResult();
class Generator : Form
{
// set this result appropriately
private TResult Result { get; set; }
public static TResult AskResult()
{
var form = new Generator();
form.ShowDialog();
return form.Result; // or fetch a control's value directly
}
}
This makes it work in a single statement, similar to a MessageBox, and does not require making any controls public. You can also include any additional data as parameters to the static method and pass them to the form's constructor or set properties appropriately.
Another benefits includes the ability to, if the need arises, reuse instances of the form.
class Generator : Form
{
public string Text1 { get; private set; }
void ok_Click (object sender, EventArgs)
{
this.Text1 = txt1.Text;
...
this.Close();
}
}
Form gen = new Generator();
gen.ShowDialog();
string text1 = gen.Text1;
...
class TextInfo
{
public string Text1 { get; set; }
...
}
class Generator : Form
{
public TextInfo Textinfo { get; private set; }
public Generator(TextInfo info)
{
this.TextInfo = info;
}
void ok_Click (object sender, EventArgs)
{
this.TextInfo.Text1 = txt1.Text;
...
this.Close();
}
}
TextInfo info = new TextInfo();
Form gen = new Generator(info);
gen.ShowDialog();
string text1 = info.Text1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With