Question Regarding My Object

Sterling33

Member
Joined
Nov 17, 2005
Messages
12
Programming Experience
3-5
Hi all,
I was wondering if someone can help me?
Heres a bit of the code im working on. When I attempt to run it, I get an error message stating that an object reference is not set to an instance of an object. Ive narrowed the problem to the code in red. Im attempting to use the Object from Form1 in Form2. Im not to sure why im getting this error when Ive declared the object as Public when I created it.
Form1
VB.NET:
Public PackageInstallerDB As New PackageInstallerDB
 
Private Sub btnNewPub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPub.Click
   Dim form2 As New form2
   Form2.ShowDialog()
End Sub
Form2
VB.NET:
Private Sub btnOkNewPub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOkNewPub.Click
[COLOR=red]  form1.PackageInstallerDB.Add_Publisher("Test")[/COLOR]
End Sub
PackageInstallerDB Class Module
VB.NET:
Public Function Add_Publisher(ByVal strMftValue As String)
   'Code to add publisher to database
End Function
-Sterling
 
when you want to use form1.PacakgeInstallerDB.Add_Publisher() you should declare it as shared in Form 1

Public Shared PackageInstallerDB As New PackageInstallerDB

Private Sub btnNewPub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPub.Click
Dim form2 As New form2
Form2.ShowDialog()
End Sub

This will allow you to access it. From an Object Oriënted point of view this is rather dirty coding. You should limit shared variables a much as possible.

Another way is to provide a parameter for the contructor of Form 2. for example:

Public PackageInstallerDB As New PackageInstallerDB

Private Sub btnNewPub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPub.Click
Dim form2 As New form2(me)
Form2.ShowDialog()
End Sub

Now you can use Form 1 in Form 2. But this also is bad coding, because now Form 1 and Form 2 are thightly coupled which will make code reuseability a lot harder.

You already have some of the solution. As you see you created a Module PackageInstallerDB
To be sure this is a module the starting must be module PackageInstallerDB and not public class PackageInstallerDB
A property of a module is that everything inside is shared. This means that you shouldn't be making an instance of the module in your Form 1. But use it directly from anywhere in the code.

So instead of using form1.PackageInstallerDB... you must access it directly:
Private Sub btnOkNewPub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOkNewPub.Click
PackageInstallerDB.Add_Publisher("Test")
End Sub
 
Back
Top