Filling a listbox with the values in a enumeration

T

Timothy Parez

Hello,

I have an enumeration for example

enum Speed
{
slow,
fast,
faster
}

Is there a way to bind this to a listbox ?
so that the listbox displays the items
"slow"
"fast"
"faster"

and holds the correct values for this enumeration

Thnx
 
I

Itai Raz

I don't believe there is (other than having a hash table or something like
that, which stores the prospective enum value and string).

--itai
 
P

ProJee

You're a lucky man:)

I've made a complete example especially for you:)
There are 3 ways to read it, specifying enum name by string, in code or
by passing variable of the type (enum).



Public Enum Speed
NoMove
Snail
Normal
Fast
Faster
SpeedOfLite
End Enum

Module SpeedyGonzales

Public Sub GetEnumMembersByEnumName(ByVal EnumName$)
Dim a%, iFieldName$, iFieldValue$

'!!! must specify your Application name before the enum name!!!!!
Dim iType As System.Type =
System.Type.GetType("WindowsApplication2." & EnumName)
Dim FI() As System.Reflection.FieldInfo = iType.GetFields()
If FI.Length > 0 Then
'dunno why, you have to start from 1 for enums, (but 0 for
classes)
For a = 1 To FI.Length - 1
With FI(a)
Dim iName$ = FI(a).Name
End With
Next a
End If
End Sub

Public Sub GetEnumMembersByEnumName()
Dim a%, iFieldName$, iFieldValue$

'the type name is is directly in code, not so flexible.
Dim iType As System.Type = GetType(Speed)
Dim FI() As System.Reflection.FieldInfo = iType.GetFields()
If FI.Length > 0 Then
'dunno why, you have to start from 1 for enums, (but 0 for
classes)
For a = 1 To FI.Length - 1
With FI(a)
Dim iName$ = FI(a).Name
End With
Next a
End If
End Sub

Private Sub GetEnumMembersByVariableOfEnum(ByVal Obj As Object)
Dim a%, iFieldName$, iFieldValue$

Dim iType As Type = Obj.GetType
Dim FI() As System.Reflection.FieldInfo = iType.GetFields()

If FI.Length > 0 Then
'dunno why, you have to start from 1 for enums, (but 0 for
classes)
For a = 1 To FI.Length - 1
With FI(a)
Dim iName$ = FI(a).Name
End With
Next a
End If
End Sub

Sub Main()
'you can do it this way
SpeedyGonzales.GetEnumMembersByEnumName("Speed")

'or this way
GetEnumMembersByEnumName()

'or maybe this way...
Dim m As Speed
GetEnumMembersByVariableOfEnum(m)
End Sub

End Module
 
Joined
Dec 2, 2008
Messages
9
Reaction score
0
You can also inherit from the Listbox class.. (It will bind the enum automatically..)

public class ListBoxEx : ListBox
{
public enum ObjectList
{
Block,
Tile,
Apple,
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top