【问题标题】:Close VB.Net form without message box if textboxes are empty如果文本框为空,则关闭没有消息框的 VB.Net 表单
【发布时间】:2020-02-26 01:32:23
【问题描述】:

我目前正在尝试修复 VB.Net 中的表单关闭事件,以便当用户尝试退出表单时 txtInput1 和 txtInput2 中有文本时,它将退出并从消息框中显示警告提示。这可行,但是如果两个框中都没有任何内容,则不应显示此提示,表单应关闭。这是我到目前为止的表单关闭事件,但它不起作用:

 'FormClosing Event
Private Sub MyForm_Closing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing


    If (txtInput1.Text = "" And txtInput2.Text = "") Then

        Me.Close()
    End If

    If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
        e.Cancel = True
    End If

End Sub

【问题讨论】:

  • _ 但它不起作用_ - 你怎么知道这不起作用?
  • 这会导致递归吗?因为当你调用Me.Close() 时,Form_Closing 事件将被触发。 ,

标签: vb.net


【解决方案1】:

首先,不要在FormClosing 事件处理程序中调用Close。如果引发该事件,则表单已经关闭,除非您特别阻止它,即除非您将 e.Cancel 设置为 True

至于问题,如果您只想在某个条件为真时显示消息,那么很明显显示它的代码必须在If 块内。想想你想做什么,然后去做。如果需要,将其写下来,这样您就可以实际比较您的代码。如果只有一个 TextBox 为空,您希望显示该消息,所以这就是您需要测试并执行的操作:

If (txtInput1.Text = String.Empty AndAlso txtInput2.Text <> String.Empty) OrElse
   (txtInput1.Text <> String.Empty AndAlso txtInput2.Text = String.Empty) Then
    If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = DialogResult.No Then
        e.Cancel = True
    End If
End If

如果你对这个条件有更深的考虑,那么你可以稍微简化一下代码。如果您从TextBoxes 创建一个Text 值列表,那么您只想在该列表包含一个空String 时显示消息:

If {txtInput1.Text, txtInput2.Text}.Count(Function(s) s = String.Empty) = 1 Then
    If MessageBox.Show("Are you sure you sure you want to exit?", "Exit", MessageBoxButtons.YesNo) = DialogResult.No Then
        e.Cancel = True
    End If
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-11-05
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    相关资源
    最近更新 更多