?
Solved

Setting connection string throws a null reference error

Posted on 2011-09-23
3
Medium Priority
?
323 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 12

Expert Comment

by:HugoHiasl
ID: 36587370
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 2000 total points
ID: 36587387
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
ID: 36587414
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Suggested Courses

762 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