2

I have a string collection in my.settings. I want to add a string to it from a text box. I have tried this:

 My.Settings.Usernames.Add(textbox1.Text)

But I am thrown this error when the code executes:

System.NullReferenceException: Object reference not set to an instance of an object.

Any ideas? I appreciate any answer, thanks.

user3105998
  • 45
  • 2
  • 9

2 Answers2

7

More than likely you have not instantiated it yet.

If you run the program at this point, the setting isn't actually created so if you try to add or remove an item from the collection you'll get the error "Object reference not set to an instance of an object."

There are a couple of ways you can fix this. First, you can create the setting object at run time if it is null, but this is a bit of a hassle.

A better solution is to click the Value text box on the Settings page. Then click the ellipsis to the right to open a String Collection Editor. If you close this without adding any strings, the Settings window still doesn't actually create the setting object. To prevent that, add a string to the String Collection Editor and click OK. Then open the editor again, remove the string, and click OK. This keeps the setting object but it's empty.

Trevor
  • 7,777
  • 6
  • 31
  • 50
2

Another way to do this on the fly is in the Form Load event or Sub Main depending on how your app starts:

' initialize the collection ias needed:      
If My.Settings.Usernames Is Nothing Then
   My.Settings.Usernames = New System.Collections.Specialized.StringCollection
End If

Forcing it to initialize by adding a fake string in Settings is a nice to know and keeps it a Design-Time task. But this is pretty simple and treats it like any other object which needs to be instanced before use.

user3697824
  • 538
  • 4
  • 15