user2076963
user2076963

Reputation: 91

passing objects between forms

So much as been written about this topic but my problem is a little different than what I can find in the previous threads. I can pass an object over to a second form but it is not available in all subs of the second form. I need it to be. The first code block in frm2 works and the animal name shows but the second code block (cmdSave) does not work - it says animal not declared. Can someone tell me what I need to change to make the last code block (cmdSave) below work?

Form 1 code:

    Dim frm2 As New frm2(animal)
    Frm2.Show()
    Me.Close()

frm2 code:

Public Sub New(ByVal animal As Object)
    InitializeComponent()
    Msgbox.show(animal.animalName)
End sub

Private sub cmdSave
    Msgbox.show(animal.animalName)
End sub

Upvotes: 2

Views: 112

Answers (1)

DAXaholic
DAXaholic

Reputation: 35348

I think you just need a (private) member in frm2 holding your passed animal object so that you are able to access it in cmdSave.

See the following code, where m_Animal is the private member.

frm2 code:

Public Class Form2
    ...
    Private m_Animal as Object

    Public Sub New(ByVal animal As Object)
        InitializeComponent()
        m_Animal = animal
        Msgbox.show(animal.animalName)
    End sub

    Private sub cmdSave
        Msgbox.show(m_Animal.animalName)
    End sub

...
End Class

Upvotes: 1

Related Questions