SIGN UP MEMBER LOGIN:    
ARTICLE

Bind an Enumeration to a Control in C#

Posted by Mahesh Chand Articles | How do I May 18, 2010
This code snippet shows how to bind an enumeration with a ComboBox Windows Forms control using C#.
Reader Level:

The GetValues method of Enum returns an array of objects. We can use this method to convert an enum to an array and bind to a ComboBox in Windows Forms using DataSource property.

The following code snippet binds ButtonState enum available in Windows Forms to a ComboBox.

comboBox1.DataSource = System.
Enum.GetValues(typeof(ButtonState));

Now, once we have an enum bound to a ComboBox, we need to the selected item from ComboBox and convert back to the enum. Unfortunately, ComboBox selected item gives us a string. Now we will have to convert back to the string value to an enum value.

For that, we can use Enum.Parse method and cast it to the enumeration.

The following code snippet takes the selected value in a ComboBox and converts it back to the enum value.


MessageBox.Show(comboBox1.Items[comboBox1.SelectedIndex].ToString());
ButtonState currentState = (ButtonState)Enum.Parse(typeof(ButtonState), comboBox1.Items[comboBox1.SelectedIndex].ToString());

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor