enumerated type as a datasource

enumerated type as a datasource

Old forum URL: forums.lhotka.net/forums/t/3593.aspx


jhw posted on Tuesday, September 25, 2007

I have a 'company' class that uses an enumerated type to set what type of company it is(eg: oil company, trucking company). When I am binding the company to the form, I need to set the datasource of the company type combobox to the enumerated type. What is the best way to do this.

So far I had to build a ro collection object and fill it with ro objects that have the enumerated value and an associated string. While this works, it is a lot of work to set it up. Is there an easier way?

 

Thanks

Heath

ben replied on Wednesday, September 26, 2007

Hi jhw,

 

I don’t know if this is the best way but it is one:

 

Enum MyEnum

   Test1

   Test2

End Enum

 

Me.cboMyCombo.DataSource = [Enum].GetNames(GetType(MyEnum))

 

With this solution your will have to parse the value selected from the ComboBox to have the real enumerated value:

 

Dim myValue As String

Dim enumValue As MyEnum

 

myValue = CStr(Me.cboMyCombo.SelectedValue)

enumValue = DirectCast([Enum].Parse(GetType(MyEnum), myValue), MyEnum)

 

I hope it will help you.

 

Benjamin

ben replied on Wednesday, September 26, 2007

Hi jhw,

 

I don’t know if this is the best way but it is one:

 

Enum MyEnum

   Test1

   Test2

End Enum

 

Me.cboMyCombo.DataSource = [Enum].GetNames(GetType(MyEnum))

 

With this solution your will have to parse the value selected from the ComboBox to have the real enumerated value:

 

Dim myValue As String

Dim enumValue As MyEnum

 

myValue = CStr(Me.cboMyCombo.SelectedValue)

enumValue = DirectCast([Enum].Parse(GetType(MyEnum), myValue), MyEnum)

 

I hope it will help you.

 

Benjamin

Copyright (c) Marimer LLC