Search code examples
vb.netfor-looppropertiesmy.settings

How can i do a for loop with vb.net's my.settings name and value?


i would like some help with this, i have tried searching on google and have tried searching here with no luck.

what i have tried so far is the following:-

For Each value As Configuration.SettingsPropertyValue In My.Settings.PropertyValues

    Dim myrecord As String = My.Settings.PropertyValues.ToString

    sql_all_matching_records = String.Format("")

Next

enter image description here but this just gets skipped when i run in debugger mode and have put a break point within the for loop.

what i want to do is be able to loop through the variable names in my.settings and then take its value and compare it to an SQL lookup. the only thing i am struggling with is looping through the my.settings.

EDIT1: ABOVE has been answered, however getting the error in picture, have a wrote the code wrong? not sure i understand what vb.net is trying to tell me. i thought it was correct.


Solution

  • A bit of a disclaimer, I'm not familiar with how/when settings are loaded and the PropertyValues collection gets filled, but it doesn't seem to hold anything until a settings value is accessed. It's a wierd workaround, but grabbing a value from settings before looping through the collection seems to fill it. Your InvalidCast exception occurs because you're trying to set myrecord = a collection.tostring. We already know that the collection has multiple values because we're iterating them, so we can't just call .tostring on it. That's like saying Array.ToString(), just doesn't work that way. I think what you're actually looking for is value.PropertyValue.ToString, that will hold the settings value you're trying to get. With both those changes applied, you get this:

        Dim dummy As String = My.Settings.dummySetting
        For Each value As System.Configuration.SettingsPropertyValue In My.Settings.PropertyValues
    
            'Dim myrecord As String = My.Settings.PropertyValues.ToString
            Dim myrecord As String = value.PropertyValue.ToString
    
            sql_all_matching_records = String.Format("")
        Next
    

    The dummySetting is just an empty value that I put in settings to call on. Hope this helps