Подтвердить что ты не робот

Как связать типы перечисления с DropDownList?

Если у меня есть следующее перечисление

public enum EmployeeType
{
    Manager = 1,
    TeamLeader,
    Senior,
    Junior
}

и у меня есть DropDownList, и я хочу связать это перечисление EmployeeType с DropDownList, есть ли способ сделать это?

4b9b3361

Ответ 1

если у вас есть объект DropDownList, называемый ddl, вы можете сделать это, как показано ниже

ddl.DataSource = Enum.GetNames(typeof(EmployeeType));
ddl.DataBind();

если вы хотите, чтобы значение Enum Back on Selection....

 EmployeeType empType = (EmployeeType)Enum.Parse(typeof(EmployeeType), ddl.SelectedValue);

Ответ 2

вы можете использовать выражение лямбда

        ddl.DataSource = Enum.GetNames(typeof(EmployeeType)).
        Select(o => new {Text = o, Value = (byte)(Enum.Parse(typeof(EmployeeType),o))});
        ddl.DataTextField = "Text";
        ddl.DataValueField = "Value";
        ddl.DataBind();

или Linq

        ddl.DataSource = from Filters n in Enum.GetValues(typeof(EmployeeType))
                select new { Text = n, Value = Convert.ToByte(n) };
        ddl.DataTextField = "Text";
        ddl.DataValueField = "Value";
        ddl.DataBind();

Ответ 3

Вот еще один подход:

Array itemNames = System.Enum.GetNames(typeof(EmployeeType));
foreach (String name in itemNames)
{
    //get the enum item value
    Int32 value = (Int32)Enum.Parse(typeof(EmployeeType), name);
    ListItem listItem = new ListItem(name, value.ToString());
    ddlEnumBind.Items.Add(listItem);
}

Я использовал эту ссылку для этого:

http://www.codeproject.com/Tips/303564/Binding-DropDownList-Using-List-Collection-Enum-an

Ответ 4

Я написал вспомогательную функцию, чтобы дать мне словарь, который я могу связать:

public static Dictionary<int, string> GetDictionaryFromEnum<T>()
{

    string[] names = Enum.GetNames(typeof(T));

    Array keysTemp = Enum.GetValues(typeof(T));
    dynamic keys = keysTemp.Cast<int>();

    dynamic dictionary = keys.Zip(names, (k, v) => new {
        Key = k,
        Value = v
    }).ToDictionary(x => x.Key, x => x.Value);

    return dictionary;
}

Ответ 5

Вот мое решение:

public static class DataBindingExtensions
{
    public static string GetDescription(this Enum source)
    {
        var str = source.ToString();
        var fi = source.GetType().GetField(str);
        var desc = fi.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
        return desc == null ? str : desc.Description; 
    }

    public static T GetValue<T>(this ComboBox comboBox)
        where T : struct, IComparable, IFormattable, IConvertible
    {
        return (T)comboBox.SelectedValue;
    }

    public static ComboBox BindTo<T>(this ComboBox comboBox) 
        where T : struct, IComparable, IFormattable, IConvertible
    {
        var list = Array.ConvertAll((T[])Enum.GetValues(typeof(T)), value => new { desp = ((Enum)(object)value).GetDescription(), value });
        comboBox.DataSource = list;
        comboBox.DisplayMember = "desp";
        comboBox.ValueMember = "value";
        return comboBox;
    }

    // C# 7.0 or highest
    public static ComboBox BindTo<T>(this ComboBox comboBox)
        where T : Enum
    {
        var list = Array.ConvertAll((T[])Enum.GetValues(typeof(T)), value => new { desp = value.GetDescription(), value });
        comboBox.DataSource = list;
        comboBox.DisplayMember = "desp";
        comboBox.ValueMember = "value";
        return comboBox;
    }
}

Тип моего перечисления:

public enum Mode
{
    [Description("Mode A")]
    A,
    [Description("Mode B")]
    B
}

Похоже:

var cb = new ComboBox();
cb.DropDownStyle = ComboBoxStyle.DropDownList;
cb.BindTo<BackupMode>();

Ответ 6

Еще проще:

 ddl.DataSource = Enum.GetValues(typeof(EmployeeType));

Затем, чтобы вернуться:

EmployeeType etSelected = (EmployeeType)ddl.SelectedValue;