DialogResult.OK按钮上的'Exit Sub'

cap*_*ssj 3 .net vb.net winforms

我有一个带有OK按钮()的VB.NETform(CopyScenarioForm),DialogResult property = OK并且还Accept Button为Form 指定了它.

mainForm使用主要的Form()显示此表单

If DialogResult.OK = CopyScenarioForm.ShowDialog() Then
      DoSomething()
End if
Run Code Online (Sandbox Code Playgroud)

现在,当用户点击CopyScenarioForm.OK按钮时,我想验证他的条目,如果我想Exit SubOK按钮的点击处理程序中无效,但是当我这样做时表单仍然关闭并DoSomething()执行.有没有办法阻止这种情况并使表单保持活动状态,只有在输入有效时才退出.我注意到,如果我改变OK按钮的DialogResult属性NONE而不是OK那么它不会导致它关闭.但那我怎么知道用户如何退出表格执行DoSomething()

Cod*_*ray 6

发生的事情是,当您在设计器中将按钮的DialogResult属性设置为"OK"时,无论如何,每次单击"确定" 按钮时都会设置此值.因此,即使您在早期使用时退出事件处理程序Exit Sub,调用表单也会看到DialogResult"正常".

正如您所发现的,首先需要在设计器中将按钮的DialogResult属性设置为"无",然后DialogResult在"确定"按钮的单击事件处理程序中手动将属性设置为正确的值.例如:

Private Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    If EntriesAreValid Then
        'Return OK to the calling form
        Me.DialogResult = DialogResult.OK
    Else
        'Show an error message, but keep the form open
        MessageBox.Show("One or more of your entries were invalid.")
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

或者,您可以DialogResult在设计器中将属性设置为"OK",并在验证失败时通过将其设置为"None"来覆盖它.这可能会产生更清晰的代码:

Private Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    If Not EntriesAreValid Then
        'Show an error message
        MessageBox.Show("One or more of your entries were invalid.")

        'Clear the DialogResult property and keep the form open
        Me.DialogResult = DialogResult.None
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)