Turn an Enum into a list in VB.Net with optional CSLA

From time to time you might have an enum that you want to databind to something as if it were a list, so I wrote some classes that turn an Enum into a list that you can databind. 

I created ways to do this in CSLA and also w/o CSLA.  I made the non-CSLA versions 1 work so that you can either use a sub class, or just use generics when defining the type of your list.  You can do the same with the CSLA versions if you want by changing some of the generics, but I didn’t bother.


'*** csla
Dim cslaList As MyTestTypeList = MyTestTypeList.GetList

'*** non-csla with inherited subclass and without
Dim list As New MyTestTypeList2
Dim list2 As New EnumList2(Of MyTestType)


'*** enum we are using
Public Enum MyTestType
something = 1
here = 2
ok = 3
End Enum

'*** csla
<Serializable()> _
Public Class MyTestTypeList
Inherits EnumList(Of mytesttype, MyTestTypeList)

End Class
<Serializable()> _
Public Class EnumList(Of T As Structure, R As EnumList(Of T, R))
Inherits Csla.NameValueListBase(Of String, Integer)

Public Shared Function GetList() As R
Return Csla.DataPortal.Fetch(Of R)()
End Function

Protected Sub New()
' require use of factory method
End Sub

<Csla.RunLocal()> _
Public Overloads Sub DataPortal_Fetch() 'ByVal criteria As Object)
Me.IsReadOnly = False
For Each item As T In [Enum].GetValues(GetType(T))
Dim name As String = [Enum].GetName(GetType(T), item)
Add(New Csla.NameValueListBase(Of String, Integer).NameValuePair(name, [Enum].Parse(GetType(T), name)))
Next
Me.IsReadOnly = True
End Sub
End Class

'*** non-csla
Public Class MyTestTypeList2
Inherits EnumList2(Of MyTestType)

End Class

Public Class EnumList2(Of T As Structure)
Inherits List(Of EnumListItem)

Public Structure EnumListItem
Dim Name As String
Dim Value As Integer
Public Sub New(ByVal name As String, ByVal value As Integer)
Me.Name = name
Me.Value = value
End Sub
End Structure

Public Sub New()
For Each item As T In [Enum].GetValues(GetType(T))
Dim name As String = [Enum].GetName(GetType(T), item)
Add(New EnumListItem(name, [Enum].Parse(GetType(T), name)))
Next
End Sub

End Class

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s