-1

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

错误是:

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

文件 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

文件 ChildForm.vb

Public Class ChildForm

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

End Class
4

3 回答 3

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
于 2013-01-23T20:29:56.167 回答
1

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

于 2013-01-23T20:29:15.570 回答
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
于 2013-01-24T03:12:37.493 回答