Add ComboBox choices at runtime in C#

[Add ComboBox choices]

This example lets you add ComboBox choices when the user selects them at runtime. To keep track of the choices for future use, it saves them in the Registry.

The example Easily save and restore a form’s settings in the Registry in C# includes some methods that make loading and saving settings in the Registry easier. This example uses the following slightly modified versions. I’ve put them in the RegistryTools class to make them easier to add to new projects.

class RegistryTools
{
    // Save a value.
    public static void SaveSetting(string app_name,
        string section, string name, object value)
    {
        RegistryKey reg_key =
            Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey app_key =
            reg_key.CreateSubKey(app_name);
        RegistryKey section_key =
            app_key.CreateSubKey(section);
        section_key.SetValue(name, value);
    }

    // Get a value.
    public static object GetSetting(string app_name,
        string section, string name, object default_value)
    {
        RegistryKey reg_key =
            Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey app_key =
            reg_key.CreateSubKey(app_name);
        RegistryKey section_key =
            app_key.CreateSubKey(section);
        return section_key.GetValue(name, default_value);
    }

    // Delete a setting.
    public static void DeleteSetting(string app_name,
        string section, string name)
    {
        RegistryKey reg_key =
            Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey app_key =
            reg_key.CreateSubKey(app_name);
        RegistryKey section_key =
            app_key.CreateSubKey(section);
        section_key.DeleteValue(name, false);
    }

    // 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);
    }
}

This example uses these methods to update the registry when the form closes and retrieves them when it loads. See the code and the previous example for the details.

In contrast 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 following code shows how the program loads the ComboBox choices when the form loads.

// 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;
}

This code uses the GetSetting method to get settings with the names Animal0, Animal1, Animal2, and so on until it finds a missing name. At that point, it has fetched all of the names and is done adding them to the ComboBox‘s choices.

The following code shows how the program updates the registry entries when the form is closing.

// 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]);
    }
}

This code deletes all settings from the program’s Animals section in the Registry. It then loops through the ComboBox‘s choices and saves them in the Registry for the next time the program runs.

The last piece of interesting code in this example is the code that updates the ComboBox choices. When the user types a new value into the ComboBox, the program adds the new value to the control’s 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);
}

This code simply loops through the ComboBox‘s choices. If the text isn’t present, the code adds it.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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