Use a setting that contains a string collection in C#

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.

<?xml version="1.0" encoding="utf-16"?>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 object.
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
// List the current items.This code takes the Items object, invokes its Cast method to convert the items into an IEnumerable of string, turns that into an array, and assigns the result to the lstItems ListBox'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.
private void ListItems()
{
lstItems.DataSource = Properties.Settings.Default.Items.Cast().ToArray();
lstItems.SelectedIndex = -1;
}
// Display the selected item.The following code shows how the program adds and removes items from the Items collection.
private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
{
txtValue.Clear();
}
else
{
txtValue.Text = lstItems.SelectedItem.ToString();
}
}
// Add an item value.Finally the following code saves the program's settings when the form is closing.
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();
}
// Save settings.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.Save();
}


Comments