Tuesday, September 2, 2025

c# - How to add items to combobox with text description from attribute

Define new enum with attributes:
/* types for printing type combobox */
public enum PrintingTypeEnum
{
  [Description( "On screen" ) ]
  TO_SCREEN,
  [Description( "On printer" ) ]
  TO_PRINT
}
Fill the combobox with items:
CPrintingType.Items.Clear();
foreach (  PrintingTypeEnum item in Enum.GetValues( typeof( PrintingTypeEnum ) ) )
{
    string description = GetEnumDescription( item );
    CPrintingType.Items.Add( description );

    /* -- default value */  
    if ( item == PrintingTypeEnum.TO_PRINT )
    {
    	CPrintingType.SelectedIndex = CPrintingType.Items.Count - 1;
    }
}

private string GetEnumDescription( Enum _value )
{
    FieldInfo field = _value.GetType().GetField( _value.ToString() );
    DescriptionAttribute attribute = field?.GetCustomAttribute<DescriptionAttribute>();
    return attribute == null ? _value.ToString() : attribute.Description;
}
Output: