views:

86

answers:

2

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?

A: 

I iterate through the enum rather than 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);
}
Ed B
@EdB This is not declarative. Thanks though.
Curtis White
+1  A: 

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
cptScarlet