Search code examples
c#.netvb.netwinformsdialogresult

Return to the first dialog


I have a WinForm that is used as a Dialog with just OK and Cancel buttons. So:

Dim sr As New SlideRangeDialog
Dim dr As Windows.Forms.DialogResult
dr = sr.ShowDialog

I have an If/Then to see if the user pressed OK. If they pressed OK and there is a validation error, I need them to go back to the dialog and fix it.

    If dr = Windows.Forms.DialogResult.OK Then
        Dim mr As Windows.Forms.DialogResult
        mr = MsgBox("Click Yes to fix, No to not fix or Cancel to go " + vbCrLf + _
                    " back to the dialog to fix.", MsgBoxStyle.YesNoCancel)
                Select Case mr
                    Case Windows.Forms.DialogResult.Yes
                        ''# something
                    Case Windows.Forms.DialogResult.No
                        ''# something more
                    Case Windows.Forms.DialogResult.Cancel
                        ''# RIGHT HERE is where I'm having the problem.
                        ''# I just want "Cancel" to return to the first dialog.
                        sr.DialogResult = Windows.Forms.DialogResult.None
                End Select
    Else
        ''#other thing
    End If

What would I put in Case Windows.Forms.DialogResult.Cancel to take me right back to the first dialog as sr.DialogResult = Windows.Forms.DialogResult.None doesn't seem to be working?

I've tried raising the event sub again (it's a click from a menu item), but this doesn't work with the technology I'm using (VSTO Ribbon).


Solution

  • Try moving your validation logic either into the dialog itself, or into a Closing event handler for the dialog. The latter might be easier. My VB.NET skills are practically non-existent so forgive me if this is off the mark:

    Dim sr As New SlideRangeDialog 
    Dim dr As Windows.Forms.DialogResult 
    AddHandler dr.Closing, AddressOf SlideRangeDialog_Closing
    dr = sr.ShowDialog 
    

    Then later:

    Public Sub SlideRangeDialog_Closing(Sender As Object, e As CancelEventArgs)
        ' cast Sender as a SlideRangeDialog and check its 
        ' DialogResult property to see if they clicked OK.
    
        ' Your validation goes in here.
        ' If anything fails validation, set e.Cancel to True and the
        ' dialog won't close.
    End Sub