You need to use Reflection
to retrieve the Description
. Since these are user-added and therefore one or more could be missing, I like to have it return the Name
if the Attribute
is missing.
Imports System.Reflection
Imports System.ComponentModel
Public Shared Function GetEnumDescription(e As [Enum]) As String
Dim t As Type = e.GetType()
Dim attr = CType(t.
GetField([Enum].GetName(t, e)).
GetCustomAttribute(GetType(DescriptionAttribute)),
DescriptionAttribute)
If attr IsNot Nothing Then
Return attr.Description
Else
Return e.ToString
End If
End Function
Usage:
Dim var As FailureMessages = FailureMessages.FailedCode1
Dim txt As String = GetDescription(var)
You can create a version to get all the Descriptions for an Enum
:
Friend Shared Function GetEnumDescriptions(Of EType)() As String()
Dim n As Integer = 0
' get values to poll
Dim enumValues As Array = [Enum].GetValues(GetType(EType))
' storage for the result
Dim Descr(enumValues.Length - 1) As String
' get description or text for each value
For Each value As [Enum] In enumValues
Descr(n) = GetEnumDescription(value)
n += 1
Next
Return Descr
End Function
Usage:
Dim descr = Utils.GetDescriptions(Of FailureMessages)()
ComboBox1.Items.AddRange(descr)
Of T
makes it a little easier to use. Passing the type would be:
Shared Function GetEnumDescriptions(e As Type) As String()
' usage:
Dim items = Utils.GetEnumDescriptions(GetType(FailureMessages))
Note that populating a combo with the names means you need to parse the result to get the value. Instead, I find it better/easier to put all the names and values into a List(Of NameValuePairs)
to keep them together.
You can bind the control to the list and use DisplayMember
to show the name to the user, while the code uses ValueMember
to get back the actual typed value.