Solved

Setting connection string throws a null reference error

Posted on 2011-09-23
3
308 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
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 500 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Close form "before" open 3 48
SQL LINE CONTINUATION ISSUE 12 37
FInd Image Control Gridview 3 21
VB.net Open video relating to control 2 19
Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

839 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