// Delete all settings in a section. public static void DeleteSettings(string app_name, string section) { RegistryKey reg_key = Registry.CurrentUser.OpenSubKey("Software", true); RegistryKey app_key = reg_key.CreateSubKey(app_name); app_key.DeleteSubKeyTree(section); } }
The example uses the following code to save and restore the items in its ComboBox when the program starts and stops.
// Load saved ComboBox entries. private void Form1_Load(object sender, EventArgs e) { // Save the current ComboBox items. for (int i = 0; ; i++) { string animal = RegistryTools.GetSetting( "howto_add_items_to_combobox", "Animals", "Animal" + i.ToString(), "").ToString(); if (animal == "") break; cboAnimal.Items.Add(animal); }
// If we have any choices, select the first. if (cboAnimal.Items.Count > 0) cboAnimal.SelectedIndex = 0; }
// Save the current ComboBox choices. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Delete previous settings. RegistryTools.DeleteSettings("howto_add_items_to_combobox", "Animals");
// Save the current ComboBox items. for (int i = 0; i < cboAnimal.Items.Count; i++) { RegistryTools.SaveSetting("howto_add_items_to_combobox", "Animals", "Animal" + i.ToString(), cboAnimal.Items[i]); } }
Note that some applications save any changes to settings as soon as they are made rather than waiting until the program ends. Then if the program crashes or is killed externally, for example by the Task Manager, the changes are not lost.
The last (and most central) piece of code in this example is the code that updates the ComboBox's choices. When the user types a new value into the ComboBox, the program adds the new value to the controls list of choices so the user can quickly select it later. The program decides the user is done entering the new choice when focus leaves the ComboBox. The following code shows the Leave event handler that detects losing focus and the UpdateCombo method that adds the new item to the ComboBox's choices if it is not already present.
// When focus leaves the control, update its item list. private void cboAnimal_Leave(object sender, EventArgs e) { UpdateCombo(cboAnimal); }
// If the ComboBox's current choice isn't in its list, add it. private void UpdateCombo(ComboBox cbo) { // See if the item is in the list. string new_text = cbo.Text; foreach (object value in cbo.Items) { // If the item is already in the list, we're done. if (new_text == value.ToString()) return; }
// If we got this far, it's not in the list so add it. cbo.Items.Add(new_text); }
Comments