locked
How to create a new my.settings at runtime? RRS feed

  • Question

  • Hi, How can I create a new my.settings at runtime?
    I'm trying with those codes

    but none of them is creating a simple string setting. 
    Also I don't understand how to put the simple name to the setting.

    Thanks


    Monday, November 2, 2020 6:51 PM

All replies

  • Hello,

    You can not create new My.Setting properties at runtime as My.Settings are created in the place shown below. To see the use the project menu in VS, select "Show all files"

    As shown here


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    Monday, November 2, 2020 7:32 PM
  • Hi Karen, could I ask you why the user in here stated as it is possible? With many upvotes?

    Also in the same topic: "While it is valid to say "it is not within the paradigm", it is not really true to say "you can't". As other answers show, it can be done, though it might seem ugly. – Jesse Chisholm Nov 7 '14 at 20:31"

    I found this but it is for WPF, I am working with Windows Form. 

    and this too.

    Thanks

    edit:

    I think I found : https://docs.microsoft.com/en-us/dotnet/api/system.configuration.applicationsettingsbase?view=dotnet-plat-ext-3.1

    But it is quite difficult to understand to me. I wounder if it could be made easier




    Monday, November 2, 2020 8:00 PM
  • Hi Mattia Fanti,

    Thanks for your feedback.

    Instead, you can save the data into userConfig file, and here's the code you can refer to.

    Imports System.Configuration
    Public Class Form1
        Private frmSettings1 As MyCustomSettings = New MyCustomSettings()
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click      
            AddOrShowSettings(Of String)(frmSettings1, TextBox1.Text, TextBox2.Text)
        End Sub
        Public Sub AddOrShowSettings(Of T)(ByVal settings As ApplicationSettingsBase, ByVal propertyName As String, ByVal val As T)
            Dim p = New SettingsProperty(propertyName) With {
                .PropertyType = GetType(T),
                .Provider = settings.Providers("LocalFileSettingsProvider"),
                .SerializeAs = SettingsSerializeAs.Xml
            }
            p.Attributes.Add(GetType(UserScopedSettingAttribute), New UserScopedSettingAttribute())
    
            If settings.Properties(propertyName) IsNot Nothing Then
                MessageBox.Show($"{propertyName} : {settings(propertyName).ToString()}")
                Return
            End If
    
            settings.Properties.Add(p)
            settings.Reload()
            Dim item = settings(propertyName)
    
            If item Is Nothing Then
                settings(propertyName) = val
                settings.Save()
            Else
                MessageBox.Show($"{propertyName} : {item.ToString()}")
            End If
        End Sub
    End Class
    Class MyCustomSettings
        Inherits ApplicationSettingsBase
    
        <UserScopedSettingAttribute()>
        Public Property name As String
            Get
                Return CType(Me("name"), String)
            End Get
            Set(ByVal value As String)
                Me("name") = value
            End Set
        End Property
    End Class

    Result of my test:

    Besides, you can use the following code to get the path of your userConfig file.

            Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
            Dim path As String = config.FilePath

    Hope it could be helpful.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, November 3, 2020 8:25 AM
  • Hi Xingyu, thanks for your answer. Can I ask you If that is basically the same for my.setting? 

    Is that creating my setting I can see at designer time too?

     In all links I provided in my second post, They say they are reloading the my.settings in order to see them at designer time. 

    Also I d like to ask you how can I make an if statement with your code, for example:

    if my.settings.number= 1 then

    etc. 

    Can I do something like this with your code? Thanks a lot

    Tuesday, November 3, 2020 1:10 PM
  • https://stackoverflow.com/questions/175726/c-create-new-settings-at-run-time

    hope it helps

    Tuesday, November 3, 2020 2:20 PM
  • Hi, That is the first link  i posted in my second post.  I already tried it doesn't work to me. It doesn't create any settings neither it write in setting file. 
    Tuesday, November 3, 2020 2:25 PM
  • Hi Mattia Fanti,

    >>If that is basically the same for my.setting

    I'm afraid not,and I will show the differences in the following examples.

    I create a new setting 'myColor' in 'Settings' window and set value to 'Color.Black'.

    Then I use the following code to change the value of 'myColor' at runtime.

        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim myCol As Color = My.Settings.myColor
            MessageBox.Show(myCol.ToString())
        End Sub
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            My.Settings.myColor = Color.Red
            MessageBox.Show(My.Settings.myColor.ToString())
        End Sub

    Result of my test.

    The 'myColor' setting is generated in userConfig file after I close the program, but the value of 'myColor' in appConfig file has not been changed.

    Here's an example of creating a new setting at runtime.

        Dim prop As SettingsProperty
        Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
            If My.Settings.Properties("MyTest") IsNot Nothing Then
                prop = My.Settings.Properties("MyTest")
            Else
                prop = New System.Configuration.SettingsProperty("MyTest")
                prop.PropertyType = GetType(String)
                My.Settings.Properties.Add(prop)
                My.Settings.Save()
            End If
            My.Settings.Properties("MyTest").DefaultValue = "MyTestValue"
            My.Settings.Save()
        End Sub
    
        Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
            MessageBox.Show(My.Settings.Properties("MyTest").DefaultValue.ToString)
        End Sub

    Result of the test.

    You can see that the settings failed to save the created value after I closed the program

    >>Can I do something like this with your code?

    Yes, you need to change some code in 'AddOrShowSettings' method.

            ...
            If item Is Nothing Then
                settings(propertyName) = val
                settings.Save()
            Else
                MessageBox.Show($"{propertyName} : {item.ToString()}")
                If Convert.ToInt32(item) = 1 Then
                    ' do something...
                End If
            End If

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 4, 2020 3:16 AM
  • Hi, I am a bit confused..  first thing first.  Is it possible to create a new setting in my.setting at runtime?

    If yes, why button 4 create new setting but it is not able to save it? Thanks

    Wednesday, November 4, 2020 3:25 AM
  • Hi Mattia Fanti,

    >>Is it possible to create a new setting in my.setting at runtime?

    Yes, all the methods in tests can change(or create) a new setting at runtime, but if you want to save the setting in userConfig file and get the new value the next time you start the program , it turns out that either you need to create a new default settings in 'Settings' window or use 'AddOrShowSettings' method to create it.

    In a word, 'AddOrShowSettings' method I provided is a better choice to create and save your settings in userConfig file.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.




    Wednesday, November 4, 2020 5:45 AM
  • Hi Mattia Fanti,

    How is the question going? Did you solve your problem? If your question has been answered then please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 5, 2020 9:30 AM