26 Ağustos 2012 Pazar

using description for enums while filling combobox

My ongoing project has a strict deadline, so we have to deliver it on time, we have no other chance..
Fortunately (or maybe unfortunately) we do not have to deliver the whole functionality at once.We deliver pieces of software gradually..
During development, i note down what to post, and i do post when i have time.. This is one of them..

writing enum descriptions:
public enum DescriptionType
    {
        [Description("Adres Türü")]
        AddressType= 1,
        [Description("Puan Türü")]
        ScoreType = 2,
        [Description("Arşiv Türü")]
        ArchiveType= 3,
...


// where the combobox is initially loaded (for me formLoad)
 this.comboDescriptionType.DataSource = Enum.GetValues(typeof( DescriptionType ));

// add this to combobox format event
 private void comboDescriptionType _Format(object sender, ListControlConvertEventArgs e)
        {
            try
            {
                 DescriptionType desc= ( DescriptionType )e.ListItem;
                e.Value = GetDescription(desc);
            }
            catch (Exception ex)
            {
                // No index selected.
            }
        }

     public static string GetDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                  (DescriptionAttribute[])fi.GetCustomAttributes(
                  typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }



Hiç yorum yok:

Yorum Gönder