Calling close on a ShowDialog()'ed form doesn't stop the code from executing on that form
So I have my main form which will open another f开发者_如何学编程orm from a menu option:
mstages = new MaterialStages( ofd.FileName );
mstages.ShowDialog();
Then in this form it checks to see if a file path is valid, if it isn't and the user can't provide one, I want the form to close.
DirectoryInfo di = null;
if ( findDataFolder() )
di = new DirectoryInfo( Program.dataPath );
else Close();
//rest of the function
I've looked and the findDataFolder() is functioning correctly returning true and false when it needs to and the else is getting executed on 'false' returns. But it doesn't close the form and continues on with the rest of the function causing errors because the DirectoryInfo doesn't have valid data.
How can I return to the main form and close this one?
Close does not stop the processing.
Use Return after Close();
if ( findDataFolder() )
di = new DirectoryInfo( Program.dataPath );
else
{
this.Close();
return;
}
Although you might want to consider restructuring your code a little:
if ( findDataFolder() )
{
di = new DirectoryInfo( Program.dataPath );
// finish processing
}
else
this.Close();
or
if ( findDataFolder() )
di = new DirectoryInfo( Program.dataPath );
if (di == null)
this.Close();
else
{
// finish processing
}
Ideally, you really want to return the results of the Dialog:
this.DialogResult = DialogResult.OK;
// or
this.DialogResult = DialogResult.Cancel;
// or
this.DialogResult = DialogResult.About;
// etc.
I think this is not a good idea to validate something in form loading event if validation result may causes the current form to be close, instead you can declare a method in this form's class and call this to validate what you want before showing form and if validation was true then show the form.
something like this.
var form2 = new Form2();
if (form2.ValidateSomething())
{
form2.ShowDialog();
}
The validation method in Form2
internal bool ValidateSomething()
{
// Return result
}
hope this help.
精彩评论