Friday, August 6, 2010

How to Bind Enums to windows Combobox?


Hello Friends,
Sometime our ComboBox lookup value are fixed and we don’t have any database table. In such situation we mostly make enum of our look up value. But most of the time we are used to bind datasource of tables or list to combbox. So we might be wonder how to bind our enum to combobox.

Here is the simple way to bind combobox. Say for example you have RoleTypes Enum.

public enum RoleTypes
{
Owner = 1,
Manager = 2,
AssitManager = 3,
Employee = 4
}
Now, to bind this enum to our combo box.

this.cmbUserRole.DataSource = Enum.GetValues(typeof(RoleTypes));

Set value to combobox.

this.cmbUserRole.SelectedItem = (RoleTypes)1;
To get value from combobox.

Convert.ToInt32((RoleTypes) this.cmbUserRole.SelectedItem);


Moreover, kindly have a look at the enum and how to create the same :


Enumerations are related symbols that have fixed values. Use enumerations to provide a list of choices for developers using your class. Moreover, it is way to avoid the hardcode values in the applicaiton. For example, the following enumeration contains a set of titles:


// C#
enum Titles : int { Mr, Ms, Mrs, Dr };


If you create an instance of the Titles type, Visual Studio displays a list of the available values when you assign a value to the variable. Although the value of the variable is an integer, it is easy to output the name of the symbol rather than its value, as shown here:


// C#
Titles t = Titles.Dr;
Console.WriteLine("{0}.", t); // Displays "Dr."

The purpose of enumerations is to simplify coding and improve code readability by enabling you to use meaningful symbols instead of simple numeric values. Use enumerations when developers consuming your types must choose from a limited set of choices for a value.

Thanks,

Paras Sanghani

1 comment:

  1. comboBox1.DataSource = Enum.GetValues(typeof(Colors));

    full source...Binding Enum to Combobox

    Ling

    ReplyDelete