How to add string to enum in C#

Dineshkumar.S 456 Reputation points
2022-09-06T11:29:25.27+00:00

In My application I want add the value for ex : " Windows + M" in enum and I want it to get displayed in the applicationj drop down box . can anyone suggest me the idea for that ?? TIA.

Developer technologies | .NET | .NET CLI
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-09-06T12:06:11.993+00:00

    Edit, let's do this with an enum - full source

    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Diagnostics;  
    using System.Windows.Forms;  
    using EnumDescriptions.Classes;  
      
    namespace EnumDescriptions  
    {  
        public partial class Form2 : Form  
        {  
            public Form2()  
            {  
                InitializeComponent();  
      
                List<KeyValuePair<string, Enum>> result =  
                    EnumHelper.GetItemsAsDictionary<WindowKeys>();  
      
                comboBox1.DisplayMember = "Key";  
                comboBox1.ValueMember = "Value";  
                comboBox1.DataSource = result;  
            }  
      
            private void button1_Click(object sender, EventArgs e)  
            {  
                MessageBox.Show(comboBox1.SelectedValue.ToString());  
            }  
        }  
      
        public enum WindowKeys  
        {  
            [Description("Windows + M")]  
            M = 1,  
            [Description("Windows + A")]  
            A = 2  
        }  
    }  
      
    

    Core code

    public class EnumHelper  
    {  
        public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>  
            Enum.GetValues(typeof(T)).Cast<T>()  
                .Cast<Enum>()  
                .Select(value => new KeyValuePair<string, Enum>(  
                    (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString())!,  
                        typeof(DescriptionAttribute)) as DescriptionAttribute)!.Description, value))  
                .ToList();  
      
    }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.