开发者

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?


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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜