As a beginner I assumed that a modal form remains open until the close method is called, but this appears not to be the case in VB.net. I have a main form and a child-form which is like a phone-book. The main form opens the child-form using the SHOWDIALOG() method. The phone-book child form has a SAVE, CANCEL and edit function buttons on it. The handler for ANY button closes the child form, even-though only the SAVE and CANCEL call the close() explicitly. When editing the phone-book data the form needs to stay open until all the edits are done and the user selects to SAVE or CANCEL.
I asked the Edge browser Copilot, and it showed a set up that creates an asynchronous method that displays the form and then awaits an asynchronous background operation. Even if I understood how that worked (almost certainly not the case), it seemed to await a single Async task instead either SAVE or CANCEL. Is there a way to keep the child form open using VB.net? Or perhaps this is not the right behavior and I have done something bad elsewhere?
When you display a form by calling ShowDialog
, calling its Close
method doesn't actually close it anyway. It will simply hide it. That's why you should ALWAYS be disposing such a form after you use it, unless you want to be able to display the same instance again, which you might. You would generally do that something like this:
Using dialogue As New SomeForm
If dialogue.ShowDialog() = DialogResult.OK Then
'...
End If
End Using
Any object created with a Using
statement is implicitly disposed at the End Using
statement.
You "close" (hide) a modal dialogue by setting its DialogResult
property. Calling the Close
method will set the DialogResult
property to Cancel
, if I remember correctly. If you set it to anything other than None
, the form will be "closed" (hidden).
What is likely happening in your case is that the DialogResult
property of those Button
is set in the designer. Clicking a Button
whose DialogResult
property is set will assign that same value to the DialogResult
property of the form, thus "closing" (hiding) it. The call to ShowDialog
will then return that value. That's how you distinguish which Button
the user clicked on the dialogue.
If you want the form to be "closed" (hidden) whenever the user clicks a particular Button
, that's how you should do it. You don't need a Click
event handler if you don't want to do anything extra but you can provide one and it will be executed before the form is "closed" (hidden). If you want to put conditional code in the Click
event handler such that the form may or may not be "closed" (hidden) on every Click
, don't set the Button's
DialogResult
property but set the form's DialogResult
property as required in your Click
event handler.