Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Setting connection string throws a null reference error

Posted on 2011-09-23
3
Medium Priority
?
329 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

618 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