17

Given the following enum:

Enum enumExample
  world
  oblivion
  holiday
End Enum

I can add its values to a list of ComboBox items like this:

combo.Items.Add(enumExample.holiday)
combo.Items.Add(enumExample.oblivion)
combo.Items.Add(enumExample.world)

Is there a shorter way?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
whytheq
  • 34,466
  • 65
  • 172
  • 267

2 Answers2

20

You can use Enum.GetValues to get a list of values for an enum then iterate the result:

For Each i In  [Enum].GetValues(GetType(EnumExample))
  combo.Items.Add(i)
Next

Or, as mentioned by @Styxxy:

combo.Items.AddRange([Enum].GetValues(GetType(EnumExample)))
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
NinjaNye
  • 7,046
  • 1
  • 32
  • 46
  • 4
    Or even shorter, use the [`AddRange`](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.addrange.aspx) method to add the array (no need for looping it yourself). – Styxxy Jan 19 '13 at 22:06
  • 'AddRange' is a lot faster btw. – gunakkoc Jan 20 '13 at 01:40
  • 6
    you can also use the `.GetNames` → `ComboBox1.Items.AddRange([Enum].GetNames(GetType(enumExample)))` – spajce Jan 20 '13 at 02:11
  • I really wish that people would stop providing answers that rely on implicit conversions. If Option Strict is turned ON, which it should be, this will not compile. Casting to an object array, as is suggested by Intellisense, causes a run time error. – Bernoulli Lizard Feb 12 '21 at 13:27
15

Why not just use:

Enum enumExample
  world
  oblivion
  holiday
End Enum

ComboBox1.DataSource = [Enum].GetValues(GetType(enumExample))

This is what I used and it seems to have worked.

Culpepper
  • 1,093
  • 12
  • 19