attempting to use array of strings in my.settings causes exception

I am Using VB.NET 2005 Express Edition. Previously I have used VB6.0 but am fairly new to VB.NET

I want to create/save/load history from data typed into a ComboBox.

I have a setting named:

My.Settings.FileToSearchFor which is of type System.Collections.Specialized.StringCollection

I load the setting with the following code into my ComboBox which is set to AutoComplete from source List

Dim obj As Object

' Load File To Search For AutoComplete settings
For Each obj In My.Settings.FileToSearchFor
cmbFileToSearchFor.Items.Add(obj.ToString)
Next

This works fine unless My.Settings.FIleToSearchFor is empty, an exception "NullReferenceException was handled" is thrown.

So I check for null value...

Dim obj As Object

' Load File To Search For AutoComplete settings

If IsDBNull(My.Settings.FileToSearchFor) Then
For Each obj In My.Settings.FileToSearchFor
cmbFileToSearchFor.Items.Add(obj.ToString)
Next
End If

OK now I get past this point. But I can't seem to add a value programatically to My.Settings.FileToSearchFor

I try

My.Settings.FileToSearchFor.Add("Test")

And I still get NullReferenceException was handled

However if I add one entry to the My.Settings.FileToSearchFor maunally like so:

1. View -> Solution Explorer (Ctrl+R)

2. Right click project name

3. Click Properties

4. Click Settings

5. Select FileToSearchFor and add a value

Then the program works fine.

I assume I need to initialize this somehow, but how

Am I trying to access this incorrectly

Thanks for any advice. Although I could see many samples on the net relating to using My.Settings none I found used System.Collections.Specialized.StringCollection

Thanks for any help!



Answer this question

attempting to use array of strings in my.settings causes exception

  • rebecca M

    Try the code below. The 'Is Nothing' check i do is a better variant than the IsDBNull check. Basically, if you haven't yet added an item ot the collection in the setting, then it won't actually create the collection, which is why it's "Nothing". You can programmitcally make a new collection (which i do below) if that's the case. And then you can add elements into it if you want.

    If My.Settings.FilesToSearchFor Is Nothing Then

    My.Settings.FilesToSearchFor = New System.Collections.Specialized.StringCollection

    End If

    My.Settings.FilesToSearchFor.Add("hello")

    For Each s As String In My.Settings.FilesToSearchFor

    MsgBox(s)

    Next

    Regards,
    Kit

    kitg@microsoft.com


  • attempting to use array of strings in my.settings causes exception