How to declare asp: listitem enum value declaratively?

I have asp: RadioButtonList and want to declaratively associate a value with an enumeration. I tried using the syntax of this type:

value = <%# ((int)MyEnum.Value).ToString() %>"

I get an error list item that does not support data binding. Any ideas?

+3
source share
2 answers

Essentially, you cannot do exactly what you want. This is because Asp: Listitem does not contain Databinding events. RadioButtonList itself supports this.

So, here is the closest I can come to what you wanted.

Here is the HTML

<asp:RadioButtonList runat="server" ID="rbl" DataSource='<%# EnumValues %>' DataValueField='Value'  DataTextField='Key' />

Here is the code behind

 Public Enum values As Integer
    first = 1
    second = 2
    third = 3
    fourth = 4
    fifth = 5

End Enum

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Page.DataBind()
End Sub

Public ReadOnly Property EnumValues() As System.Collections.Generic.Dictionary(Of String, String)
    Get


        Dim val As values

        Dim names As Array
        Dim values As Array


        Dim stuff As Dictionary(Of String, String) = New Dictionary(Of String, String)

        names = val.GetNames(val.GetType)
        values = val.GetValues(val.GetType)

        build the final results
        For i As Integer = 0 To names.Length - 1
            stuff.Add(names(i), values(i))
        Next

        Return stuff

    End Get
End Property
+1
source

I iterate through an enumeration, not a binding.

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));
    radioButtonList1.Items.Add(item);
}
0

Source: https://habr.com/ru/post/1749655/


All Articles