Search code examples
c#winformsvisual-studioapplication-settings

How can I store an array of strings at runtime to a single application settings property?


I want to store user input of server names once saved from inside an application. I get an error in the settings for index out of bounds in my SettingsForm class (error line indicated below). I believe my ServerName property is only of size one so how would I go about changing this? Or is something else need to be changed in my code?

I am unsure about storing the multiple strings to one property. I have been trying different things but I am new to C# and WinForms applications. Here is the code I have been trying to work out:

UserSettings class:

[UserScopedSetting()]
    [DefaultSettingValue("Enter Server Name")]
    public String[] ServerName
    {
        get
        {
            return (String[])this["ServerName"];
        }
        set
        {
            this["ServerName"] = (String[])value;
        }
    }

SettingsForm class:

private void saveSettingsButton_Click(object sender, EventArgs e)
    {
        //loop through all servers
        for (int i=0; i<serverCounter.Value; i++)
        {
            TextBox currentTextBox = (TextBox)servers[i, 0];
            us.ServerName[i] = currentTextBox.Text; //ERROR
            currentTextBox.DataBindings.Add("Text", us, "ServerName");

        }
        us.Save();

        this.Close();
    }

Solution

  • Potential issues: what value does serverCounter.Value have? How is us.ServerName[] instantiated? ServerName returns a string array, but to me it looks like each serverName should be a string, and then put into an array (or list).

    From the code snippet you show, my guess is that serverCounter has a certain value >1 and us.ServerName always is an array with 1 item (or it is never instantiated). This will give you an index out of range error.

    Try using public string ServerName instead of public String[] ServerName and then each time you get a return value, put that value into an array--or if you don't know how many servers will be inputted, a List would be better.

    List<string> serverNames = new List<string>();
    
    // Get currentName from user--I don't understand how your code is supposed to work
    
    serverNames.Add(currentName);  // this is the name entered by the user
    

    Then use a foreach loop:

            foreach (string name in serverNames)
            {
                //do something
            }
    

    If you know in advance how many servers there are, you can use a string array:

    string[] serverNames = new string[serverCounter];
    

    and still use a foreach loop to iterate over it.