How do you bind an Enum to a DropDownList control in ASP.NET?

后端 未结 25 2599
既然无缘
既然无缘 2020-11-29 15:41

Let\'s say I have the following simple enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

How can I bind this enum to a DropDow

25条回答
  •  难免孤独
    2020-11-29 16:27

    I probably wouldn't bind the data as it's an enum, and it won't change after compile time (unless I'm having one of those stoopid moments).

    Better just to iterate through the enum:

    Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
    Dim itemNames As Array = System.Enum.GetNames(GetType(Response))
    
    For i As Integer = 0 To itemNames.Length - 1
        Dim item As New ListItem(itemNames(i), itemValues(i))
        dropdownlist.Items.Add(item)
    Next
    

    Or the same in C#

    Array itemValues = System.Enum.GetValues(typeof(Response));
    Array itemNames = System.Enum.GetNames(typeof(Response));
    
    for (int i = 0; i <= itemNames.Length - 1 ; i++) {
        ListItem item = new ListItem(itemNames[i], itemValues[i]);
        dropdownlist.Items.Add(item);
    }
    

提交回复
热议问题