Windows窗体构造函数不接受参数

时间:2013-01-23 20:21:05

标签: .net vb.net constructor

如果使用参数创建Form对象,为什么在填充Form值时出错?

错误是:

  

对非共享成员的引用需要一个对象引用。

File ParentForm.vb

Public Class Maincls
Dim oChildForm as New ChildForm("abc") ' Causes an error, but removing the arguments removes the error
Dim oChildForm as New ChildForm ' Does not throw an error
Public Sub btnok_click
ChildForm.tbXYZ.Text = "abc"    ' Reference to non-shared member needs an object reference
End Sub

End Class

File ChildForm.vb

Public Class ChildForm

    Public Sub New(tempString as String)
        InitializeComponent()
    End Sub

End Class

3 个答案:

答案 0 :(得分:4)

在btnok的处理程序中,您使用的是类名而不是您创建的实例的名称。这应该做到。

Public Class Maincls

    Dim oChildForm as New ChildForm("abc") 'Causes Error, but removing the arguments removes the error
    Dim oChildForm as New ChildForm 'Does not thow error

    Public Sub btnok_click
        oChildForm.tbXYZ.Text = "abc"    'Reference to non-shared member needs an object reference
    End Sub

End Class

答案 1 :(得分:1)

在按钮单击事件中,将ChildForm更改为oChildForm。

答案 2 :(得分:0)

对于构造函数,您必须定义一个值,例如:

Sub New() ' You can use "Overload" if it needs to be shared or no shared
          ' for a non-shared member

End Sub

Public Class ChildForm

    Private valStr As String

    Public Sub New(ByVal str As String)
        Me.valStr = str ' Shared Memeber
    End Sub

    Public Property Text As String
        Get
            Return valStr
        End Get
        Set(ByVal value As String)
            valStr = value
        End Set
    End Property

End Class

使用方法:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles Button2.Click

    Dim a As New ChildForm("Contoh")
    MsgBox(a.Text)
End Sub

或者:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles Button2.Click

    Dim a As New ChildForm
    a.Text = "Test"
    MsgBox(a.Text)
End Sub