1: Imports System.Reflection
2:
3: ''' <summary>
4: ''' A custom dropdown that binds to an enum
5: ''' </summary>
6: ''' <remarks>
7: ''' The DataSource is set to an Enum type name, not a collection,
8: ''' and it can be set within the markup if desired
9: ''' <example><![CDATA[
10: ''' <app:EnumList Runat="server" ID="ddlRegion" DataSource="MyApp.RegionCode" />
11: ''' ...
12: ''' ddlRegion.DataBind()
13: ''' ddlRegion.SelectedValue = RegionCode.West
14: ''' ]]></example>
15: ''' </remarks>
16: Public Class EnumList
17: Inherits System.Web.UI.WebControls.DropDownList
18:
19: Private _enumType As Type
20: ''' <summary>
21: ''' Specify the enum type that we'll bind to
22: ''' </summary>
23: ''' <value></value>
24: ''' <returns></returns>
25: ''' <remarks></remarks>
26: Public Shadows Property DataSource() As String
27: Get
28: Return _enumType.ToString
29: End Get
30: Set(ByVal value As String)
31: _enumType = System.Type.GetType(value, True, True)
32: End Set
33: End Property
34:
35: ''' <summary>
36: ''' Replace SelectedValue with an Enum-based version
37: ''' </summary>
38: ''' <value></value>
39: ''' <returns></returns>
40: ''' <remarks></remarks>
41: Public Shadows Property SelectedValue() As System.Enum
42: Get
43: ' Get the value from the request to allow for disabled viewstate
44: Dim RequestValue As String = Me.Page.Request.Params(Me.UniqueID)
45:
46: Return System.Enum.Parse(_enumType, RequestValue)
47: End Get
48: Set(ByVal value As System.Enum)
49: MyBase.SelectedValue = value.ToString
50: End Set
51: End Property
52:
53: ''' <summary>
54: ''' Replace DataBind so that we can bind to the list of fields in the
55: ''' enum. Call our GetDescription function for each one to get the
56: ''' text to display.
57: ''' </summary>
58: ''' <remarks></remarks>
59: Public Overrides Sub DataBind()
60: Me.Items.Clear()
61: Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Static
62:
63: For Each field As FieldInfo In _enumType.GetFields(flags)
64: Me.Items.Add(New ListItem(GetDescription(field), field.Name))
65: Next
66: End Sub
67:
68: End Class