单击计算按钮时显示MessageBox的异常处理

时间:2020-04-04 07:00:05

标签: vb.net winforms exception try-catch

This is the form

我设计了这个Windows窗体应用程序。如果单击了计算按钮,并且文本框中没有文本,则使用try catch块显示错误消息框。但是,当我单击按钮而不在文本框中输入文本时,什么也没发生。这是我的代码;

    Dim textBox As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    'throws an exception if text box input is empty
    Try
        textBox = CStr(TextBox1.Text)
    Catch ex As Exception
        MessageBox.Show("enter text in text box")
        TextBox1.Focus()
    End Try

    'if there's no error execute some code below

End Sub

1 个答案:

答案 0 :(得分:1)

处理此问题的正确方法是使用Validating的{​​{1}}事件。您处理事件,并在其中验证数据,如果失败则将TextBox设置为e.Cancel。这样可以防止字段在输入有效数据之前失去焦点。然后,您可以在True事件处理程序中调用ValidateChildren,以强制验证所有控件,即使它们尚未获得焦点。它将返回一个Button.Click,指示所有子代是否都通过验证。

Boolean