打开表单的按钮,如果打开则关闭

时间:2013-09-08 17:22:41

标签: vb.net if-statement

我是VB.net的新手,有一个问题,希望你能帮助我。

我有一个打开按钮的表单,当我按下按钮表单2打开时。然后我想要表格1上的按钮,然后在表格2打开时按下表格2。

我在按钮单击子项中有以下代码..

Dim openForm As Form2
openForm =New Form2()


If Application.OpenForms. OfType(Of Form2).Any() Then

Form2.Close()

Else

openForm.Show()
openForm = Nothing

End If

第一次按下按钮时,表单2会打开。然而,再次按下按钮不起作用,表格不会关闭。

任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

您始终在创建Form2的新实例,但您应该关闭现有实例,并仅在您要打开新表单时创建新实例。

' We are keeping our opened form reference here!
Dim openForm As Form2

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        If Application.OpenForms.OfType(Of Form2).Any() Then
              ' No `openForm = new Form2` here - we need to close the existing instance
              ' and not to create new one
              openForm.Close()
        Else
            ' Create new instance only here!
            openForm = New Form2()
            openForm.Show()
        End If

或者

    Dim openForms = Application.OpenForms.OfType(Of Form2)()
    ' If there is Form2 instance opened
    If openForms.Any() Then
        ' Get it and close it!
        openForms.First().Close()
    Else
        Dim openForm As New Form2
        openForm.Show()
    End If

答案 1 :(得分:0)

试试这个

    If Application.OpenForms.OfType(Of Form2).Any() Then
        Application.OpenForms.OfType(Of Form2).ElementAt(0).Close()
    Else
        Form2.Show()
    End If