Add a public flag of success in a Form2
and check it afterwards. Or you can use built-in functionality of ShowDialog
and DialogResult
.
It is more proper in terms of OOP and logic than changing the value of Form1
from a Form2
.
If you change the value of hardcoded form then you will be unable to reuse this form again.
With this approach you can reuse this form again in any place.
Using simple custom variable:
public class Form2 : Form
{
public bool Result { get; set; }
public void ButtonYes_Click(object sender, EventArgs e)
{
Result = true;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
Result = false;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
form.ShowDialog();
if (form.Result) TextBox1.Text = String.Empty;
}
}
}
Using DialogResult
or ShowDialog
:
public class Form2 : Form
{
public void ButtonYes_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.No;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
var result = form.ShowDialog();
if (result == DialogResult.Yes) TextBox1.Text = String.Empty;
}
}
}
It also a good idea to use using
as form is not disposed after ShowDialog
.
It makes disposing deterministic. This way you can ensure it is disposed right after you stopped using it.