Let’s say you want to save a person’s gender in your database. You could save it as a string, but that’s very wasteful. Ideally you’d save it as tinyint, because it will never have more values, so why waste space and computing time with joins, or other solutions. Your enum could look like this
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; namespace Data.Enums { public enum Genders : byte { [DescriptionAttribute("No Answer")] NoAnswer = 0, [DescriptionAttribute("Male")] Male = 1, [DescriptionAttribute("Female")] Female = 2 } }
Great, now you have an enum, but next how do you populate a drop-down list from it? The answer is simple. With the use of the following method, read the attributes from each value
public static string GetEnumString(Type enumtype, byte? selectedValue) { string ret = ""; if (selectedValue != null) { try { foreach (dynamic item in Enum.GetValues(enumtype)) if ((byte)item == selectedValue) ret = EnumUtils.stringValueOf(item); } catch { } } return ret; }
Next, create a helper method to populate it for you, which you can re-use in every project
public static List GetGenders(byte selectedValue) { List list = new List(); foreach (Genders item in Enum.GetValues(typeof(Genders))) list.Add(new SelectListItem() { Text = EnumUtils.stringValueOf(item), Value = ((byte)item).ToString(), Selected = (byte)item == selectedValue }); return list; }
Quick Links
Legal Stuff