我尝试在允许模式框关闭之前验证某些数据,但它似乎在验证发生之前关闭。这是我的代码
Public Class my_popup
Inherits Form
Dim result = Me.ShowDialog()
If result = DialogResult.OK Then
If key = Nothing Then
If last_name.Text <> "" Then
MessageBox.Show("The user is not in the database.")
' Abort closing and leave dialog open.
End If
Else
save_it()
End If
End If
End Class
当消息框显示时,模态表单已经关闭。我如何防止这种情况发生?
答案 0 :(得分:0)
Your code seems a bit odd. Usually a modal dialog is called from a parent form that requires some input and wait until the modal dialog has completed its work. If you need some kind of validation in the modal dialog and keep the modal dialog open if the validation fails then you should write something like this
In the calling form:
Using frm = new my_popup()
if frm.ShowDialog() = DialogResult.OK Then
..... if we enter here the validation is OK...
End If
End Using
then, in the my_popup
class, usually you have an OK button (for this example called buttonOK) that is set as the AcceptButton for the form and its property DialogResult is set to DialogResult.OK.
Then, when you click the OK button, you write your validation, in the event handler of the button
Protected Sub buttonOK_Click(sender as Object, e as EventArgs) Handles buttonOK.Click
If last_name.Text <> "" Then
MessageBox.Show("The user is not in the database.")
' Abort closing and leave dialog open.
Me.DialogResult = DialogResult.None
Else
Dim saved = save_it()
if saved = false Then
MessageBox.Show(....fail to save....)
Me.DialogResult = DialogResult.None
End If
End If
End Sub
The key point here is to set the property DialogResult of the my_popup form to DialogResult.None. This will block the automatic closing of the form and your user could type the necessary fixes to the input....