|
-
Feb 4th, 2011, 11:34 AM
#1
Thread Starter
Frenzied Member
Convert Integer to Value from Enum
I have add some items into an combbox, the items represent the values from ContentAlignment Enum, (the values of the combobox are not same as the values of the Enum)
Upon selection of a value from the combobox, i want to set the TextAlignment of the Button
Plz Help
-
Feb 4th, 2011, 11:38 AM
#2
Re: Convert Integer to Value from Enum
I don't quite understand what you want Value to be. Regardless, you can convert an enum to its int value like so:
Code:
CInt(MyEnum.MyValue)
or create an enum from a number or string
Code:
DirectCast(System.Enum.Parse(GetType(MyEnum), "MyValue"), MyEnum)
-
Feb 4th, 2011, 11:55 AM
#3
Re: Convert Integer to Value from Enum
Code:
'use the enum as values for the combobox
ComboBox1.DataSource = [Enum].GetValues(GetType(ContentAlignment))
'set index for test
ComboBox1.SelectedIndex = 1
'change the alignment
Button1.TextAlign = CType(ComboBox1.SelectedIndex, ContentAlignment)
If you don't want all the values from the enum then
Code:
'use the enum as values for the combobox, excluding some values
Dim ds = [Enum].GetValues(GetType(ContentAlignment)). _
Cast(Of ContentAlignment)().Where(Function(ca) ca <> ContentAlignment.BottomLeft AndAlso ca <> ContentAlignment.BottomRight)
ComboBox1.DataSource = ds.ToList
Last edited by dbasnett; Feb 4th, 2011 at 12:08 PM.
-
Feb 4th, 2011, 12:41 PM
#4
Re: Convert Integer to Value from Enum
dbasnett's code is the way to go except that you should be casting the SelectedItem rather than the SelectedIndex. In some cases the result will be the same but not in all, so stick with the one that will always work, i.e. SelectedItem.
-
Dec 8th, 2019, 08:27 AM
#5
New Member
Re: Convert Integer to Value from Enum
Hey all I know this is an old thread but it comes up fairly high in results. I wanted to drop this code example for anyone finding this .
Code:
//Valid
Color c = (Color)3;
//Result: c = Blue
//Invalid
Color c = (Color)4;
//Result: c = 4
Snippet borred from:C# int to enum
-
Dec 8th, 2019, 11:48 AM
#6
Re: Convert Integer to Value from Enum
Yeah, that's a snippet, but this is a VB forum, so a C# snippet isn't quite so appropriate. How about turning it into VB?
My usual boring signature: Nothing
 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|