Use a string collection setting in C#

[string collection]

A program’s settings can include many data types such as int, char, DateTime, and Color. If you want to be able to hold a list of strings, you can make a setting that has type StringCollection.


To create such a setting, open the Project menu and select Properties at the bottom to see the following Properties page., and click the Settings tab.




Enter the name you want to give the property in the left text box. Select the data type System.Collections.Specialized.StringCollection in the left dropdown. Use the right dropdown to set the setting’s scope to User (not shared) or Application (shared by all users).

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. If you look closely at the value shown in the Settings page, you’ll see something like this:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

This defines an empty array of strings and that makes the program create the setting object with no entries in it.

After going through all this to create the object, using is is fairly easy. The following code shows how the program lists the strings in the Items setting.

// List the current items.
private void ListItems()
{
    lstItems.DataSource =
        Properties.Settings.Default.Items.Cast<string>().ToArray();
    lstItems.SelectedIndex = -1;
}

This code takes the Items object, invokes its Cast method to convert its items into an IEnumerable of string. It then turns that into an array and assigns the result to the lstItems ListBox control’s DataSource property to display the items. The code then makes sure no item is selected in the list.

If the user clicks on an item in the ListBox, the following code displays it in the program’s text box.

// Display the selected item.
private void lstItems_SelectedIndexChanged(object sender,
    EventArgs e)
{
    if (lstItems.SelectedItem == null)
        txtValue.Clear();
    else
        txtValue.Text = lstItems.SelectedItem.ToString();
}

The following code shows how the program adds and removes items from the Items collection.

// Add an item value.
private void btnAdd_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.Items.Add(txtValue.Text);
    txtValue.Clear();
    txtValue.Focus();
    ListItems();
}

// Remove an item value.
private void btnRemove_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.Items.Remove(txtValue.Text);
    txtValue.Clear();
    txtValue.Focus();
    ListItems();
}

Finally the following code saves the program’s settings when the form is closing.

// Save settings.
private void Form1_FormClosing(object sender,
    FormClosingEventArgs e)
{
    Properties.Settings.Default.Save();
}


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in settings and tagged , , , , , , , , , . Bookmark the permalink.

4 Responses to Use a string collection setting in C#

  1. john rodriguez says:

    Is necessary add using System.Linq; Linq for use Cast()

  2. This is very helpful and well-written — thank you! I have a StringCollection setting exactly like this which has worked for years, using NET 4.61. When I add another element using the ellipsis button, though, I get an unhandled exception error when I try to index the new element. I’ve tried everything I can think of. Do you know how I can reset the list indexer to see the new list size, or is there a better way to change the size of a StringCollection?

    • RodStephens says:

      When you first install (or perhaps run) the program, it creates a user.config file to hold the settings. If you later change the settings in Visual Studio, those settings are not copied into app.config. In your case the file still contains the old settings so you get the error when you try to access the new one, which isn’t there. For example, if you had 5 settings and added one, Visual Studio now has 6 settings but user.config still has the original 5.

      If you remove the user.config file, then when you run the program again I think it will use the new settings to rebuild that file.

      Or you could edit user.config and add the new value there.

      In recent versions of Windows, open File Explorer and go to %USERPROFILE%\AppData\Local\. There you should see a directory named after the program. Drill down into that until you find the file. On my system the file for this example is at:

      C:\Users\rod\AppData\Local\howto_list_setting\howto_list_setting.vshost_Url_eklnmicfxhpfalr2ibir4kmsec51yx4k\1.0.0.0\user.config

  3. That did it Ron, thanks! I found and edited the user.config corresponding to the program version I’m developing, and all was well

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.