ARTICLE

Binding an Enum to a ComboBox

Posted by Mahesh Chand Articles | How do I October 06, 2009
The following code snippet shows how to bind an enumeration to a ComboBox in WPF or Windows Forms using C#.
Reader Level:
Download Files:
 

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 WPF using ItemsSource property.

The following code snippet binds InkCanvasEditingMode enum available in WPF to a ComboBox.

InkEditingModeList.ItemsSource = System.Enum.GetValues(typeof(InkCanvasEditingMode));

Note: If you are using Windows Forms, use DataSource property, instead of ItemsSource.

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.

string str = InkEditingModeList.Items[InkEditingModeList.SelectedIndex].ToString();

InkBoard.EditingMode = (InkCanvasEditingMode)Enum.Parse(typeof(InkCanvasEditingMode),                 InkEditingModeList.Items[InkEditingModeList.SelectedIndex].ToString());

 

Download the attached project for full sample.

Login to add your contents and source code to this article
post comment
     

Thanks Barry.

Posted by Mahesh Chand Jun 20, 2010

I think you can just cast the value for Windows forms.
I don't know about WPF but it's all C#.
I assume the compiler automatically does what your code does.


Here is my sample to fill the combo:

// combo formatting for running item actions

m_comboBoxAfterRunningItem.DataSource = System.Enum.GetValues(typeof(eTestManagerRunningItemActions));
m_comboBoxAfterRunningItem.FormattingEnabled =
true;
m_comboBoxAfterRunningItem.Format +=
delegate(object sender, ListControlConvertEventArgs formatArgs)
{
formatArgs.Value = Utility.PropertyGridHelpers.
EnumDescriptionConverter.GetEnumDescription((Enum)formatArgs.Value);
};

// set initial value
m_comboBoxAfterRunningItem.SelectedItem = m_TestManager.runningItemAction;



// and here is my sample for getting the result

m_TestManager.runningItemAction = (eTestManagerRunningItemActions)m_comboBoxAfterRunningItem.SelectedItem;


Posted by barry lowry Oct 07, 2009
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts