Search code examples
asp.netdata-bindingradiobuttonlistdeclarative

How to set an asp:listitem to an enumeration value declaratively?


I have an asp:RadioButtonList and want to declaratively bind the value to an enumeration. I tried using this type syntax:

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

I get an error list item does not support databinding. Any ideas?


Solution

  • Essentially you cannot do exactly what you want to. This is because Asp:Listitem does not contain the Databinding event. The RadioButtonList itself does support this however.

    So here is the closest I could 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