473,545 Members | 2,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting enum value through enum type

Dear all,

I have the following codes:

======

public enum Enum_Value
{
Value0 = 0,
Value1 = 10,
Value2 = 5,
Value3 = -1
}
private void comboImageType_ SelectedIndexCh anged(object sender,
System.EventArg s e)
{
setCombo(comboV alue, typeof(Enum_Val ue));
}

private void setCombo(ComboB ox combo, Type enumType)
{
object val;
Enum_Value enumValueObject ;

//only do this if combo selection is valid
if (combo.Selected Index >= 0)
{
//Get element of Enum_Value pointed by selected index.
//So let say if SelectedIndex is 2 then I should get 5
val = Enum.GetValues( enumType).GetVa lue(combo.Selec tedIndex);

//Assign back this value to enumValueObject
//enumValueObject = val; <-- ERROR : Cannot implicitly convert type
'object' to ...

enumValueObject = (Enum_Value ) val; // <--- is this is OK?

int iVal = (int) enumValueObject ;
Console.Write(" Enum value is " + iVal.ToString() );
}
}

======

This really start as a question.. But while typing the question I got
some idea, try it and get it to work. So I might have already solve the
problem.

Basically I have to get enum value from ComboBox selected item. As you
can see above my problem is I try to assign object to enumValueObject .

So the question now is, am I doing the right thing? Perhaps there is
better way or shorter way of doing things?

Thanks in advance.

Jul 17 '06 #1
7 9816
"Harris" <ha*********@gm ail.comha scritto nel messaggio

Basically I have to get enum value from ComboBox selected item. As you
can see above my problem is I try to assign object to enumValueObject .

So the question now is, am I doing the right thing? Perhaps there is
better way or shorter way of doing things?
If I understand you can simply cast an enum value to and from an int type,
so you can do:

Enum_Type val = (Enum_Type)comb o.SelectedIndex ;

combo.SelectedI ndex = (int)val;
Jul 17 '06 #2
Hi,

>
Enum_Type val = (Enum_Type)comb o.SelectedIndex ;
I do not think this may work, as the OP use not a consecutive numbering.

A possible solution:

enum_type val = Enum.GetValues( typeof(enum_typ e) )[ combo.SelectedI ndex ];

Of course, this assume that the shown values are in teh same order they were
declared

--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Jul 17 '06 #3
Ignacio Machin ( .NET/ C# MVP ) wrote:
Hi,


Enum_Type val = (Enum_Type)comb o.SelectedIndex ;

I do not think this may work, as the OP use not a consecutive numbering.

A possible solution:

enum_type val = Enum.GetValues( typeof(enum_typ e) )[ combo.SelectedI ndex ];
My mistake here to use Enum_Type in place of Enum_Value in my
previous post. So might as well I correct this.

Enum_Value val = Enum.GetValues( typeof(enum_typ e) )[
combo.SelectedI ndex ];

IMHO, This wont work because GetValues returnSystem.Ar ray. The error is
: Cannot apply indexing with [] to an expression of type
'System.Array'.

Of course, this assume that the shown values are in teh same order they were
declared
Yes, the comboBox value is ordered same as Enum_Value ordered. For
instance combo box contents will be this

Value0
Value1
Value2
Value3
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Thanks for all the help. Really appreciate it.

Jul 18 '06 #4
Here lies my latest dilemma :). I know that .Net is very flexible
langguage. So I always like to flex it and somewhat find it broken
point.

In summary my question is can I create and enum variable using enum
type?

Please read my inserted comments.

Harris wrote:
Dear all,

I have the following codes:

======

public enum Enum_Value
{
Value0 = 0,
Value1 = 10,
Value2 = 5,
Value3 = -1
}
private void comboImageType_ SelectedIndexCh anged(object sender,
System.EventArg s e)
{
setCombo(comboV alue, typeof(Enum_Val ue));
}

private void setCombo(ComboB ox combo, Type enumType)
{
object val;
Enum_Value enumValueObject ;
I cannot do this becuase the enumObject may be of other type. Basically
what I want to do here is;

enumType enumValueObject ;
// Error : The type or namespace name 'enumType'
// could not be found (are you missing a using directive
// or an assembly reference?)

>
//only do this if combo selection is valid
if (combo.Selected Index >= 0)
{
//Get element of Enum_Value pointed by selected index.
//So let say if SelectedIndex is 2 then I should get 5
val = Enum.GetValues( enumType).GetVa lue(combo.Selec tedIndex);

//Assign back this value to enumValueObject
//enumValueObject = val; <-- ERROR : Cannot implicitly convert type
'object' to ...

enumValueObject = (Enum_Value ) val; // <--- is this is OK?
same here, because I am casting using Enum_Value which can be other
enum type.

So what I want to do here is something like this:

enumValueObject = (enumType ) val;
// Error : The type or namespace name 'enumType'
// could not be found (are you missing a using directive
// or an assembly reference?)

Come to think of it I get enumType by doing typeof(Enum_Val ue). So
enumType is not Enum_Value. But I can't think a way of getting back
Enum_Value out of enumType.

:) Any help is appreciated.
>
int iVal = (int) enumValueObject ;
Console.Write(" Enum value is " + iVal.ToString() );
}
}

======
Thanks again.
Thanks in advance.
Jul 18 '06 #5
There are at least 2 areas of confusion in your post:

(1) The values returned by Enum.GetValues( ) aren't necessarily in the
declared order.

(2) You don't need to cast an object to an enumeration value before
casting it to an integer in order to get the underlying integral value.

Perhaps you will find this example illustrating:

---8<---
using System;

enum Enum_Value
{
Value0 = 0,
Value1 = 10,
Value2 = 5,
Value3 = -1
}

public class App
{
static void Main()
{
foreach (string name in Enum.GetNames(t ypeof(Enum_Valu e)))
Console.WriteLi ne(name);
Console.WriteLi ne("---");
object x = Enum.GetValues( typeof(Enum_Val ue)).GetValue(2 );
Console.WriteLi ne(x);
Console.WriteLi ne(x.GetType()) ;
Console.WriteLi ne((int) x);
}
}
--->8---

It prints:

---8<---
Value0
Value2
Value1
Value3
---
Value1
Enum_Value
10
--->8---

-- Barry

--
http://barrkel.blogspot.com/
Jul 18 '06 #6
Barry Kelly wrote:
There are at least 2 areas of confusion in your post:

(1) The values returned by Enum.GetValues( ) aren't necessarily in the
declared order.
Thanks, I dont realize this untill you point it out.

Fortunately my code so far do not depend on this since I do
Enum2Combo() and then later Combo2Enum(). So the order stay the same
during the process. My code is at the end of this post.
(2) You don't need to cast an object to an enumeration value before
casting it to an integer in order to get the underlying integral value.

Perhaps you will find this example illustrating:
I find it very illustrating :) . I have run this code changing Value3
to 1. It appeares that enum members are sorted according to their
value.

So if Value3 = 1. They are sorted to The ouput is

Value0 : 0
Value3 : 1
Value2 : 5
Value1 : 10

If Value3 = -1 and Value0 is -5

Value2 : 5
Value1 : 10
Value0 : -5
Value3 : -1

Beats me why it is sorted in such way. Ofcourse the bonus question is
whether they should be sorted at all. This is annoying.
---8<---
using System;

enum Enum_Value
{
Value0 = 0,
Value1 = 10,
Value2 = 5,
Value3 = -1
}

public class App
{
static void Main()
{
foreach (string name in Enum.GetNames(t ypeof(Enum_Valu e)))
Console.WriteLi ne(name);
Console.WriteLi ne("---");
object x = Enum.GetValues( typeof(Enum_Val ue)).GetValue(2 );
Console.WriteLi ne(x);
Console.WriteLi ne(x.GetType()) ;
Console.WriteLi ne((int) x);
}
}
--->8---

It prints:

---8<---
Value0
Value2
Value1
Value3
---
Value1
Enum_Value
10
--->8---

-- Barry

--
http://barrkel.blogspot.com/

=============== =

private enum Enum_Value
{
Value0 = 0,
Value1 = 10,
Value2 = 5,
Value3 = -1
}

private Enum_Value enumObject;

private void Form1_Load(obje ct sender, System.EventArg s e)
{
Enum2Combo(comb oBox1, typeof(Enum_Val ue), Enum_Value.Valu e3);
}

private object Combo2Enum(Comb oBox combo, Type enumType)
{
if (combo.Selected Index >= 0)
{
try
{
return Enum.ToObject(
enumType,
(int)(Enum.GetV alues(enumType) .GetValue(combo .SelectedIndex) ));
}
catch (Exception ex)
{
throw new Exception("Erro r setting enum from combo index. "
+ ex.Message, ex);
}
}

throw new Exception("Erro r setting enum due to invalid combo
index.");
}

private void Enum2Combo(Comb oBox combo, Type enumType, object
defaultValue)
{
int i=0;
foreach(string itemName in Enum.GetNames(e numType))
{
combo.Items.Add (itemName.Repla ce("_"," "));
Console.WriteLi ne(defaultValue .ToString());

if (itemName == defaultValue.To String())
combo.SelectedI ndex = i;

i++;
}
}

private void button1_Click(o bject sender, System.EventArg s e)
{
enumObject = (Enum_Value) Combo2Enum(comb oBox1, typeof(Enum_Val ue));
Console.WriteLi ne("---");
Console.WriteLi ne(enumObject.T oString() + " : " +
((int)enumObjec t).ToString());
}

=============== =

It does look over kill :D. But I learn a lot about enum while doing the
code. At the same time I am still somewhat dissatisfied with this code.
If I ever change it to something else, I will post some update here.

:D Much ado about nothing.

Take care.

Jul 19 '06 #7
Here is my code for a combo box for enumerated values. Hope there's
something of value for you here.

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Reflecti on;
using System.Windows. Forms;

namespace MyStuff.Control s
{
/// <summary>
/// A combo box that gives the user a choice between items
/// in an enumerated type. The combo
/// box offers auto-completion and sorting, and allows the
/// caller to interact purely in terms of enumerated values.
/// </summary>
/// <remarks>
/// Auto-completion is enabled only if the combo box's
/// <see cref="ComboBox. DropDownStyle"/is <see
cref="ComboBoxS tyle.DropDown"/>
/// or <see cref="ComboBoxS tyle.Simple"/>.
/// </remarks>
public class ComboBoxForEnum : ComboBox
{
#region Delegate

/// <summary>
/// Delegate that converts the enumerated values to display strings.
/// </summary>
public delegate string EnumToDisplaySt ringDelegate(En um enumValue);

#endregion

#region Private members

private Type _enumType;
private Enum[] _itemArray;
private EnumToDisplaySt ringDelegate _toDisplayStrin g;
private Enum _noneValue;
private bool _displayNoneVal ue;

#endregion

#region Constructor

/// <summary>
/// Creates a new combo box with a <c>null</citems collection,
/// and the default display member of <c>"Description "</c>.
/// </summary>
public ComboBoxForEnum ()
{
this._enumType = null;
this._itemArray = null;
this._toDisplay String = null;
this._noneValue = null;
this._displayNo neValue = false;
}

#endregion

#region Public properties and methods for managing combo box items

/// <summary>
/// Gets or sets the enumerated type for which to populate the combo
box
/// with enumerated values.
/// </summary>
/// <value>A <see cref="Type"/derived from <see cref="Enum"/>, or
/// <c>null</cif the type has not yet been set.</value>
[Description("Th e enumerated type for which to populate the combo box
with enumerated values."), Category("Appea rance"), DefaultValue(nu ll)]
public Type EnumeratedType
{
get { return this._enumType; }
set
{
if (value == null)
{
if (this.DesignMod e)
{
this._enumType = value;
}
else
{
throw new ArgumentNullExc eption("value", "Enumerated type for
combo box cannot be null.");
}
}
else if (value.IsEnum)
{
this._enumType = value;
if (this._toDispla yString != null)
{
RebuildComboBox Contents();
}
}
else
{
throw new ArgumentExcepti on(String.Forma t("Type '{0}' is not an
enumerated type.", value), "value");
}
}
}

/// <summary>
/// Gets or sets a method that converts an enumerated value of type
/// <see cref="Enumerate dType"/to a string to display in the combo
box.
/// </summary>
/// <value>A method that converts an enumerated value to a string,
/// or <c>null</cif the method has not yet been set.</value>
[Browsable(false ),
DesignerSeriali zationVisibilit y(DesignerSeria lizationVisibil ity.Hidden)]
public EnumToDisplaySt ringDelegate EnumToDisplaySt ring
{
get { return this._toDisplay String; }
set
{
if (value == null)
{
throw new ArgumentNullExc eption("value", "Display string
conversion method for combo box cannot be null.");
}
else
{
this._toDisplay String = value;
if (this._enumType != null)
{
RebuildComboBox Contents();
}
}
}
}

/// <summary>
/// Gets or sets the value that should be returned if the user
/// does not choose anything in the combo box.
/// </summary>
/// <value>An enumerated value of the type given by
/// <see cref="Enumerate dType"/>.</value>
[Description("Th e enumerated value that the combo box should return
if nothing is selected."), Category("Behav ior"), DefaultValue(nu ll)]
public Enum NoneValue
{
get { return this._noneValue ; }
set
{
if (value == null)
{
this._noneValue = null;
RebuildComboBox Contents();
}
if (this._enumType == null)
{
throw new InvalidOperatio nException(Stri ng.Format("Atte mpt to set
'NoneValue' to '{0}' when 'EnumeratedType ' has not yet been set.",
value));
}
else if (this._enumType .IsInstanceOfTy pe(value))
{
this._noneValue = value;
RebuildComboBox Contents();
}
else
{
throw new ArgumentExcepti on(String.Forma t("Value '{0}' is not one
of the enumerations of type {1}.", value, this._enumType) , "value");
}
}
}

/// <summary>
/// Gets or sets an indication of whether the combo box should
display the
/// <see cref="NoneValue "/as one of the entries that the user can
choose.
/// Normally, the <see cref="NoneValue "/represents a null choice by
the user
/// and is not represented in the list of valid choices. Callers may
want to
/// set this property to <c>true</cin cases in which the <see
cref="NoneValue "/>
/// is a valid default value, rather than a value indicating "nothing
chosen."
/// </summary>
/// <value><c>tru e</cif the combo box should display an entry
corresponding
/// to the <see cref="NoneValue "/>; <c>false</cif the entry
/// corresponding to the <see cref="NoneValue "/should be suppressed
/// and therefore the <see cref="NoneValue "/is returned only when
there
/// is nothing selected in the combo box.</value>
[Description("Sh ould the combo box display the NoneValue as one of
the items the user can choose?"), Category("Behav ior"),
DefaultValue(fa lse)]
public bool DisplayNoneValu e
{
get { return this._displayNo neValue; }
set { this._displayNo neValue = value; }
}

/// <summary>
/// Gets or sets the currently selected enumerated value in the combo
box.
/// </summary>
/// <value>The enumerated value currently selected in the combo box,
or
/// <see cref="NoneValue "/if there is currently nothing selected in
/// the combo box.</value>
[Browsable(false ),
DesignerSeriali zationVisibilit y(DesignerSeria lizationVisibil ity.Hidden)]
public new Enum SelectedItem
{
get
{
int index = base.SelectedIn dex;
if (this._itemArra y == null)
{
if (this.DesignMod e)
{
return null;
}
else
{
throw new InvalidOperatio nException("Att empt to fetch selected
item when combo box has not been properly initialized.");
}
}
else if (index < 0)
{
return this._noneValue ;
}
else if (index < this._itemArray .Length)
{
return this._itemArray[index];
}
else
{
throw new Exception(Strin g.Format("Combo box selected index was
{0}, but item array is only {2} items long.", index,
this._itemArray .Length));
}
}

set
{
if (this._itemArra y == null)
{
if (!this.DesignMo de)
{
throw new InvalidOperatio nException("Att empt to set selected item
when combo box has not been properly initialized.");
}
}
else
{
int index = 0;
while (index < this._itemArray .Length &&
!this._itemArra y[index].Equals(value))
{
index += 1;
}
if (index >= this._itemArray .Length)
{
ClearSelection( );
}
else
{
base.SelectedIn dex = index;
}
}
}
}

/// <summary>
/// Clears the selection in the combo box back to a blank.
/// This methods selects entry -1 in the combo box, showing
/// blank contents.
/// </summary>
public void ClearSelection( )
{
// If the combo box is the type that you can enter free text in,
then
// clear the text
if (base.DropDownS tyle != ComboBoxStyle.D ropDownList)
{
this.Text = "";
}

// Do it twice to get around a bug in .NET v1.1
base.SelectedIn dex = -1;
base.SelectedIn dex = -1;
}

#endregion

#region Private methods to populate combo box

/// <summary>
/// Rebuilds the combo box contents based on the current item array
and the current
/// display member.
/// </summary>
private void RebuildComboBox Contents()
{
base.Items.Clea r();
if (this._enumType != null && this._toDisplay String != null)
{
Array enumArray = Enum.GetValues( this._enumType) ;
int displayLength = enumArray.Lengt h;
if (!this._display NoneValue && this._noneValue != null &&
Array.IndexOf(e numArray, this._noneValue ) >= 0)
{
displayLength -= 1;
}
this._itemArray = new Enum[displayLength];
string[] displayArray = new string[displayLength];
int d = 0;
for (int i = 0; i < enumArray.Lengt h; i++)
{
Enum enumValue = (Enum)enumArray .GetValue(i);
if (this._displayN oneValue || !enumValue.Equa ls(this._noneVa lue))
{
this._itemArray[d] = enumValue;
displayArray[d] = this._toDisplay String(enumValu e);
d++;
}
}
if (base.Sorted)
{
Array.Sort(this ._itemArray, displayArray);
}
base.Items.AddR ange(displayArr ay);
}
}

#endregion
}
}

Jul 19 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
4805
by: Glenn Venzke | last post by:
I'm writing a class with a method that will accept 1 of 3 items listed in an enum. Is it possible to pass the item name without the enum name in your calling statement? EXAMPLE: public enum EnumName FirstValue = 1 SecondValue = 2 ThirdValue = 3
0
5485
by: lglmi | last post by:
'********************START OF BAS MODULE******************** Option Explicit Private Type OSVERSIONINFO dwOSVersionInfoSize As Long dwMajorVersion As Long dwMinorVersion As Long dwBuildNumber As Long dwPlatformId As Long
6
796
by: James Brown | last post by:
Hi, I have the following enum declared: enum TOKEN { TOK_ID = 1000, TOK_NUMBER, TOK_STRING, /*lots more here*/ }; What I am trying to do is _also_ represent ASCII values 0-127 as TOKENs (this is why I started the TOKEN enum off at '1000' so I had plenty of space at the
21
4572
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
31
3572
by: Michael C | last post by:
If a class inherits from another class, say Form inherits from control, then I can assign the Form to a variable of type Control without needing an explicit conversion, eg Form1 f = new Form1(); Control c = f; An enum value inherits from int but it doesn't get implicitly converted: HorizontalAlignment h = HorizontalAlignment.Center;
18
11314
by: Visual Systems AB \(Martin Arvidsson\) | last post by:
Hi! I have created an enum list like this: enum myEnum : int { This = 2, That, NewVal = 10, LastItm
10
23563
by: kar1107 | last post by:
Hi all, Can the compiler chose the type of an enum to be signed or unsigned int? I thought it must be int; looks like it changes based on the assigned values. Below if I don't initialize FOO_STORE to be, say -10, I get a warning about unsigned comparison and I'm seeing an infinite loop. If I do initialize FOO_STORE = -10, I don't see...
34
11140
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a...
3
1454
by: Adrian | last post by:
In the following code example I am trying to create a generic interface for a bunch of objects. Each concrete type is stored in its own container and the a container of pointer's to base is used so I can access all at once. I created a specialization of the template for Fruit *'s so that it returns a reference and the code looks the same as...
0
7468
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7808
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7423
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
4945
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1884
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1014
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
704
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.