Thursday, 11 October 2007

'if the enum is :
Public Enum aslamEnum
Created = 0
AwaitingPayment
Active
InProduction
Complete
Cancelled
End Enum


'The function will return description if exist else the name:

Private Function GetEnumDescription(ByVal Value As aslamEnum) As String
Dim objFieldInfo As FieldInfo
Dim sRetVal As String
Dim objDescriptionAttributes() As DescriptionAttribute
Dim tEnum As Type = GetType(aslamEnum)

objFieldInfo = tEnum.GetField([Enum].GetName(tEnum, Value))
objDescriptionAttributes = objFieldInfo.GetCustomAttributes(GetType(DescriptionAttribute), False)
With objDescriptionAttributes
If .Length > 0 Then
sRetVal = objDescriptionAttributes(0).Description
Else
sRetVal = [Enum].GetName(tEnum, Value)
End If
End With

Return Trim(sRetVal)
End Function


'To get the value back either in Name or Description use
value=GetEnumDescription(varmyEnum)

No comments: