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


Categories: Programming | .Net | VB.Net
Friday, November 27, 2009 3:16:10 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview
All content © 2010, Christopher May, Inc
Open Job Positions
On this page
Google Ads
This site
Calendar
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: