VB-从父级查找子级表单

时间:2019-01-29 16:53:47

标签: vb.net forms

我在一个具有多种形式的项目中。

我在这里创建一个TicTacToe表单:

 Private Sub MenuTicTacToe(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim page As Form = New TicTacToe
    page.Show(Me)
End Sub

这是一个TicTacToe表单:

Public Class TicTacToe

    Public opponent as String
    'Some code where user set opponent

    Public Function Receive(S As String)
    if string = opponent
        'Some code
    End Function

End Class

我想以我的主要形式调用函数Receive 如果我这样做:

TicTactoe.Receive(S) 它会在没有对手的情况下调用Receive的实例。

我想找到TicTacToe的对应形式并致电Receive

谢谢

3 个答案:

答案 0 :(得分:1)

在线评论

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    page.Receive("Joe")
End Sub
'A form level variable to hold a reference to the instance of TicTacToe
'Although vb.net can use default instances, you have created an explicit
'instance of TicTacToe so you need to keep a reference if you want to
'refer to this instance.
Private page As TicTacToe
Private Sub MenuTicTacToe(ByVal sender As Object, ByVal e As System.EventArgs)
    page = New TicTacToe()
    page.Show(Me)
End Sub

Partial Public Class TicTacToe
    Inherits Form
    Public opponent As String
    'Functions must be declared as a Type
    'If you do not need a return value use a Sub
    Public Function Receive(S As String) As String
        Dim someString As String = ""
        If S = opponent Then
            'Do something
        End If
        'There must be a return Value
        Return someString
    End Function

End Class

答案 1 :(得分:0)

使用它来显示表单

Dim page As TicTacToe
Private Sub MenuTicTacToe(ByVal sender As Object, ByVal e As System.EventArgs)
    page = New TicTacToe
    page.Show(Me)
End Sub

然后您就可以使用

page.Receive(S)

修改

使用多种形式

For Each f As TicTacToe in Application.OpenForms().OfType(Of TicTacToe)
        f.Receive (S)
Next

答案 2 :(得分:0)

在C#中,您将需要一个新实例,但是就像在VB中一样,编译器已经为您完成了此操作。

您当前正在做的是创建TicTacToe表单的新实例并显示它:

Private Sub MenuTicTacToe(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim page As Form = New TicTacToe
    page.Show(Me)
End Sub

但是您不会在任何地方保存该实例。然后,在下一段代码中,您将使用另一个实例,该实例是由编译器创建的静态实例:

TicTacToe.Receive(S) // TicTacToe is the static instance

因此,您最终要调用两个不同的实例,这说明了为什么没有设置对手的原因。

要解决此问题,请不要创建新实例。在您的Private Sub MenuTicTacToe中,只需使用由编译器创建的实例,就不会出现此问题,就像这样:

Private Sub MenuTicTacToe(ByVal sender As Object, ByVal e As System.EventArgs)
    TicTacToe.Show(Me)
End Sub

希望这会有所帮助。