Solved

Setting connection string throws a null reference error

Posted on 2011-09-23
3
299 Views
Last Modified: 2012-05-12
The last line of the code is setting the global variable.  It is the line that creates the error.  The odd thing is that the error only occurs if the reg key is not set yet.  If the key is set everything works fine.  The global variable is create like this.

Dim dbconnection As New OleDb.OleDbConnection

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=Post Office
  StackTrace:
       at Post_Office.Form1.Form1_Load(Object sender, EventArgs e) in c:\users\mdmiller\documents\visual studio 2010\Projects\Post Office\Post Office\Form1.vb:line 61
       at System.EventHandler.Invoke(Object sender, EventArgs e)
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Post_Office.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

'get registery data
        Dim regKey As RegistryKey
        regKey = Registry.LocalMachine.OpenSubKey("Software\PostOffice", True)
        If regKey Is Nothing Then 'it doesnt exist  
            createregistry("PostOffice")
            Dim openFileDialog1 As New OpenFileDialog
            openFileDialog1.Filter = "MS Access Database (*.accdb)|*.accdb"
            openFileDialog1.RestoreDirectory = True
            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                writeregistry("PostOffice", openFileDialog1.FileName, "PathtoDB")
            Else
                MsgBox("You Must Select a Database, this program will close now")
                'if they don't select a database end the program
                Application.Exit()
            End If
        End If
        ''setup connectionstring
        dbconnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & regKey.GetValue("PathtoDB", 0.0))

Open in new window

0
Comment
Question by:Millkind
3 Comments
 
LVL 12

Expert Comment

by:HugoHiasl
Comment Utility
There are multiple possible reasons.

I assume the reason for the exception is that regKey is Nothing and you try to access GetValue of Nothing.

What happens if it is not found in line 3? It creates it but it does not assign it to regKey. It remains Nothing.
0
 
LVL 5

Accepted Solution

by:
DerZauberer earned 500 total points
Comment Utility
the regKey variable is still Nothing when reaching last line, reread it after writing value to registry

... Then
writeregistry("PostOffice", openFileDialog1.FileName, "PathtoDB")
regKey = Registry.LocalMachine.OpenSubKey("Software\PostOffice", True)
Else ...

0
 
LVL 15

Expert Comment

by:x77
Comment Utility
Note that regKey  is nothing, you can take openFileDialog1.FileName


        Dim regKey As RegistryKey, PathtoDB  as string
        If regKey IsNot Nothing Then 'it doesnt exist  
            PathtoDB  = regKey.GetValue("PathtoDB", 0.0))
        else
            createregistry("PostOffice")
            Dim openFileDialog1 As New OpenFileDialog
            openFileDialog1.Filter = "MS Access Database (*.accdb)|*.accdb"
            openFileDialog1.RestoreDirectory = True
            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                PathtoDB  =  openFileDialog1.FileName
                writeregistry("PostOffice", PathtoDB  , "PathtoDB")

....
        ''setup connectionstring
        dbconnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathtoDB)
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now