What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleList the values defined by an arbitrary Enum in VB .NET
DescriptionThis example shows how to list the values defined by an arbitrary Enum in VB .NET. It uses reflection to get a list of the values at run time rather than requiring you to hard code the values at design time.
KeywordsEnum, reflection
The ListEnumValues function takes a parameter giving the type of an Enum. It calls the type's GetFields method to get an array of FieldInfo objects describing the Enum's fields (public variables).

The program checks each FieldInfo object's IsLiteral property to see if it is a literal design time defined value (try commenting this out) and adds the literal fields' values to the result array. Note that this value object has the same type as the Enum. If the Enum is HatchStyle, then the values have type HatchStyle.

Imports System.Reflection
' Return a list of an enumerated type's values.
Public Function ListEnumValues(ByVal enum_type As Type) As _
    ' Enumerate the Enum's fields.
    Dim field_infos() As FieldInfo = enum_type.GetFields

    ' Loop over the fields.
    Dim results() As Object
    Dim max_result As Integer = -1
    For Each field_info As FieldInfo In field_infos
        ' See if this is a literal value (set at compile
        ' time).
        If field_info.IsLiteral Then
            ' Add it.
            max_result += 1
            ReDim Preserve results(max_result)
            results(max_result) = _
        End If
    Next field_info

    Return results
End Function
When the program starts, it uses function ListEnumValues to get an array of the HatchStyle values. It passes each to the DrawHatchStyleSample subroutine, which draws samples of the HatchStyles. See the code for details about that routine.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    ' Make a Bitmap and associated Graphics object.
    Dim samples_size As New Size( _
        5 * (WID + DX), 12 * (HGT + DY))
    Dim bm As New Bitmap(samples_size.Width, _
    Dim gr As Graphics = Graphics.FromImage(bm)

    ' Enumerate the HatchStyle fields.
    Dim hatch_styles() As Object = _

    ' Loop over the HatchStyle fields.
    For Each hatch_style As HatchStyle In hatch_styles
        DrawHatchStyleSample(gr, hatch_style)
    Next hatch_style

    ' Display the result.
    picSamples.Image = bm
    picSamples.ClientSize = samples_size
    Me.ClientSize = picSamples.Size

    ' Clean up.
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.