如何访问另一个类的方法?

时间:2015-08-05 19:10:40

标签: vb.net

我在“Form2”中遇到了另一个类“So​​cketClient”的访问方法的麻烦,但在“Form1”中工作得非常好!换句话说,我可以使用“SocketClient”的方法从“Form1”发送数据,但是我不能从“Form2”做同样的事情。

如何解决?

这是我的代码:

“Form1中”

Public Class Form1

Public WithEvents C As New SocketClient
Public Yy As String = "|SPLIT|"

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  C.Send("ref" & Yy & "data here")

End Sub
End Class

“窗体2”

 Public Class Form2 

    Public frm1 As Form1

     Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click

     ' The error is here, don't sends data to server application
      frm1.C.Send("ref" & frm1.Yy & "Name: " & TextBox1.Text)

    End Sub
    End Class

1 个答案:

答案 0 :(得分:1)

假设您已将Form1作为主窗体,并且您正在从该主窗体创建Form2,请尝试通过构造函数传递引用:

Public Class Form2
  Private frm1 As Form1

  Public Sub New(mainForm As Form1)
    Me.InitializeComponent()
    frm1 = mainForm
  End Sub

End Class

从主窗体(form1)中,您将传递引用:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
  Dim form2 As New Form2(Me)
  form2.Show()
End Sub