-2

Please see the code below:

Public Sub GetConnectionString(Dim strCon As String)
            Dim stringtochange As String = ConfigurationManager.ConnectionStrings("GeniedbConnection").ConnectionString 'line 2
            Dim configFile As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            Dim connectionStringsSection As ConnectionStringsSection
            connectionStringsSection = CType(configFile.GetSection("GeniedbConnection"), ConnectionStringsSection)
            connectionStringsSection.ConnectionStrings("GeniedbConnection").ConnectionString = strCon 'Line 6
            configFile.Save()
        End Sub

I am trying to change the connection string in the app.config. Line 2 returns the current connection string. Line 6 throws an exception: `"Object reference not set to an instance of an object." Why is this?

w0051977
  • 13,017
  • 23
  • 108
  • 265
  • 3
    see this... http://stackoverflow.com/questions/16131382/object-reference-not-set-to-an-instance-of-an-object-app-config – SoftSan Jul 18 '14 at 11:49
  • 2
    It is because an object reference is not set to an instance of an object. There's a ton of similar questions on SO, and most of them end up giving the same, correct, advice. Debug your code, see which object reference is not set, and figure out where to go from that. – Lasse V. Karlsen Jul 18 '14 at 11:54
  • 2
    I agree with Lasse. There's a question devoted to this topic, http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Patrick Jul 18 '14 at 11:55

1 Answers1

0

Line 2

Dim stringtochange As String = ConfigurationManager.ConnectionStrings("GeniedbConnection").ConnectionString

is different with line 6

connectionStringsSection.ConnectionStrings("GeniedbConnection").ConnectionString = strCon

ConfigurationManager != connectionStringsSection

either of these is null, connectionStringsSection, connectionStringsSection.ConnectionStrings("GeniedbConnection")

Yuliam Chandra
  • 13,858
  • 12
  • 49
  • 66