Initialize a ComboBox from an enumeration in C#

example

Often it’s useful to initialize a ComboBox from an enumeration so the user can pick one of the enumeration’s values. You could type the value into the ComboBox at design time, but then if the enumeration changes, you’ll have to remember to update the values. A better alternative is to initialize the ComboBox in code.

The following code shows how this example does this.

// The list of user types.
private enum UserTypes
{
    SalesAndShippingClerk,
    ShiftSupervisor,
    StoreManager
}

// Initialize the cboUserType ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
    foreach (string user_type in Enum.GetNames(typeof(UserTypes)))
    {
        cboUserType.Items.Add(user_type.ToProperCase());
    }
}

This code first defines the UserTypes enumeration.

When the program starts, it uses the Enum.GetNames method to get a list of the enumeration’s values. For each item, the code calls the ToProperCase string extension method described in the example Convert between Pascal case, camel case, and proper case in C# to convert the Pascal cased enum values into proper case strings. For example, this converts SalesAndShippingClerk to Sales And Shipping Clerk.

When the user selects a ComboBox entry, the following code converts the selection into a UserTypes value and then displays a string to show that it performed the conversion correctly.

// Get the selected user type.
private void cboUserType_SelectedIndexChanged(
    object sender, EventArgs e)
{
    // Convert the ComboBox's text into the Pascal cased name.
    string type_name = cboUserType.Text.ToPascalCase();

    // Convert the name into a UserTypes value.
    UserTypes user_type =
        (UserTypes)Enum.Parse(typeof(UserTypes), type_name);

    // Prove it worked.
    switch (user_type)
    {
        case UserTypes.SalesAndShippingClerk:
            lblSelectedType.Text =
                "You selected sales && shipping clerk.";
            break;
        case UserTypes.ShiftSupervisor:
            lblSelectedType.Text =
                "You selected shift supervisor.";
            break;
        case UserTypes.StoreManager:
            lblSelectedType.Text =
                "You selected store manager.";
            break;
    }
}

The code gets the selected value and uses the ToPascalCase extension method to convert it back into the name used by the enumerated type. (For example, it converts Shift Supervisor to ShiftSupervisor.) It then uses the Enum.Parse method to convert the string value into a UserTypes value. The code finishes by using a switch statement to verify that it found the correct type.


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 *