On main form i've got button and methods:
private void button2_Click(object sender, EventArgs e)
{
ShowMyDialogBox();
}
public void ShowMyDialogBox()
{
testDialog= new Form3_addrow(tran_in);
DialogResult dr = testDialog.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
testDialog.Close();
}
else if (dr == DialogResult.OK)
{
testDialog.Close();
bool w= kd.dodaj(tran_in);
if (w) MessageBox.Show("Transakcja dodana");
else MessageBox.Show("Coś poszło nie tak...");
}
}
and button on Form3_addrow:
private void AcptBtn_Click(object sender, EventArgs e)
{
zczytaj();
this.AcptBtn.DialogResult = System.Windows.Forms.DialogResult.OK;
}
Everything works but i must click twice this button. in debugger mode i saw that first time i click, button handler is called, but nothing more. Second time, handler is called again and then control returns to ShowMyDialogBox() method.
To add to what @user3185569 wrote:
You can set the Form.CancelButton
and Form.AcceptButton
properties for your Form3_addrow
form to point to your Cancel
and OK
buttons respectively. In that case you don't even need Click
event handlers, the form will simply set the DialogResult
automatically when you click on either of the buttons.
You don't have to invoke Close
on the dialog instance manually, but simply Dispose
it when you're done.
A usual way to use a modal dialog is through the using
directive, to ensure that it's disposed immediately after use:
using (var addRowForm = new Form3_addrow(tran_in))
{
var result = testDialog.ShowDialog(this);
if (result == DialogResult.OK)
{
// no need to call Close here
DoStuff();
}
}
The reason you need to do this is that a modal dialog (i.e. one shown using ShowDialog()
as opposed to just Show()
) merely hides itself when you close it (or set the DialogResult
property to a value), to allow you to access its properties even when it's not being shown anymore, as explained on MSDN.