ShowDialog – Auto close or stopping the close

I have come across this issue recently and decided to post something on it.  I also found a few posts on the internet on it, but to me, they never really explained it properly.  Not to mention that the solution is pretty simple, but I find often the more complex the problem the easier it can be to find the solution, that the simpler ones could take longer not because they are hard but because it is so simple, not to mention it is staring you in the face and you can’t seem to see it.  So this is why I am posting it.

I have a dialog;

image

There is it.  I used to have the property DialogResult automatically set to DialogResult.Cancel and DialogResult.OK for the buttons.  When using the ShowDialog method, clicking either of these buttons will close the dialog automatically, and return the result based on the button pressed.

The issue I came across was performing field validation on the Value field when clicking OK.  But the message would show but the dialog would still close.  I fixed this by,

  1. Removing the property values of DialogResult from the buttons.  Setting them to None.
  2. Putting in the click events into each button the return of the dialog result.
Private Sub OKButton_Click(ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles OKButton.Click
	If ValidateValue() Then
		Me.DialogResult = DialogResult.OK
	End If
End Sub

Private Sub CancelButton_Click(ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles CancelButton.Click
	Me.DialogResult = DialogResult.Cancel
End Sub

Then the code in the main form, would handle the result coming back.  Note that in the OKButton that is ValidateValue is False then the dialog will stay there.

That is how I solved it, I hope this may come of use to anyone who was using ShowDialog for a form and has problems with it automatically closing when the buttons have the DialogResult property set to a value at design time.

Advertisements

Posted on August 30, 2012, in Article, Development, Tips and Tricks and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: