In this article I will explain with an example, how to populate (bind) ComboBox from Enum in Windows Forms (WinForms) Application using C# and VB.Net.
The Enum values will be extracted into an Array and then each Array item will be added to the ComboBox in Windows Forms (WinForms) Application using C# and VB.Net.
Form Controls
The below Form consists of a ComboBox control.
Enum
Following is a simple Enum of 3 colors Red, Green and Blue to which I have assigned integer values 1, 2 and 3 respectively.
C#
public enum Colors
{
Red = 1,
Blue = 2,
Green = 3
}
VB.Net
Public Enum Colors
Red = 1
Blue = 2
Green = 3
End Enum
Populate (Bind) ComboBox from Enum in Windows Forms (WinForms) Application
Inside the Form Load event, the values of the Enum are fetched into an Array and then a loop is executed over the Array items and one by one each item is added to a List collection of Key Value Pairs.
Finally the List collection of Key Value Pairs is bound to the ComboBox control.
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<KeyValuePair<string, string>> lstColors = new List<KeyValuePair<string, string>>();
Array colors = Enum.GetValues(typeof(Colors));
foreach (Colors color in colors)
{
lstColors.Add(new KeyValuePair<string, string>(color.ToString(), ((int)color).ToString()));
}
cmbColors.DataSource = lstColors;
cmbColors.DisplayMember = "Key";
cmbColors.ValueMember = "Value";
}
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim lstColors As New List(Of KeyValuePair(Of String, String))()
Dim colors As Array = [Enum].GetValues(GetType(Colors))
For Each color As Colors In colors
lstColors.Add(New KeyValuePair(Of String, String)(color.ToString(), CInt(color).ToString()))
Next
cmbColors.DataSource = lstColors
cmbColors.DisplayMember = "Key"
cmbColors.ValueMember = "Value"
End Sub
Screenshot
Downloads