Blog Archive

Blog posts tagged with 'dropdownlist'

RSS
Filling a drop down list from enums - Sunday, March 6, 2011

 I'm always trying to find a better way (or different way) to do something, and I've been interested in the uses of enums lately - so I came up with a way to fill a drop down list control with a list of enums.

public static void FillDropDownFromEnum(DropDownList ddl, Type enumType, bool IsRequired, string selected, bool sameValue = false, bool separateCaps = false)
        {
            ddl.Items.Clear();
            if (!IsRequired)
            {
                ddl.Items.Add("---");
            }

            foreach (int value in Enum.GetValues(enumType))
            {
                ListItem li = new ListItem();
                string liText = string.Empty;

                if (separateCaps)
                    liText = SpaceBeforeCaps(Enum.GetName(enumType, value));
                else
                    liText = Enum.GetName(enumType, value);

                li.Text = liText;

                if (sameValue)
                    li.Value = liText;
                else
                    li.Value = value.ToString();

                if (!string.IsNullOrEmpty(selected))
                    if (selected == liText)
                        li.Selected = true;

                ddl.Items.Add(li);
            }
        }

public static string SpaceBeforeCaps(string caps)
        {
            int i = 1;
            while (i < caps.Length)
            {
                if (Char.IsUpper(caps[i]))
                {
                    caps = caps.Insert(i, " ");
                    i++;
                }
                i++;
            }
            return caps;
        }

Comments (0)