BLOG.CSHARPHELPER.COM: Initialize a ComboBox's values from an enumerated type in C#
Initialize a ComboBox's values from an enumerated type in C#
Often it's useful to let the user select an enumerated value from a ComboBox. In that case, you may also want to initialize the list in code so it can display the enumerated type's current values in case you change them.
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) { List user_types = GetEnumValues(); foreach (UserTypes user_type in user_types) { cboUserType.Items.Add(user_type.ToString().ToProperCase()); } }
When the program starts, it uses the GetEnumValues method described in the example Use reflection to list the values defined by an enum in C# to make a list of the enumerated type's values. It then loops through those values adding them to the ComboBox's item list.
For each item, the code calls the ToProperCase string extension method described in the example Convert strings 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 takes action.
// 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 string extension to convert it into the name used by the enumerated type. It then uses the Enum.Parse method to convert the string value into a UserTypes value. It finishes by using a switch statement to verify that it found the correct type.
Very informative article, thanks for sharing! I'd be able to use this in my business site.
Reply to this