473,394 Members | 1,800 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Looping through enums

Hi all

Who can Help me with this one?
if I have this Enums:
#region Title
public enum Title: short
{
NA = 0,
Mr = 2,
Adv = 3,
Brig = 4,
Dr = 5,
Genl = 6,
Prof = 7,
Miss = 8,
Mrs = 9,
Adm = 10,
Rev = 11,
Ms = 12,
}
Now I want to take the textbox.text and loop through the enums(Not the
value) to check if it exist in my enums
Something like this:

Public bool DoesTitle Exist
{
blnValid = false
For each enum
{
if (textbox.text == enum.name(Example: "MR"))
return true
break
}

return blnValid ;

}
}
Thanks a mill for those who can help

Jan 31 '06 #1
7 4704
Well, to do what you want I would actually use Enum.Parse:

Enum.Parse(typeof(Title),theText)

However, to enumerate, just use

Enum.GetNames(typeof(Title))
or
Enum.GetValues(typeof(Title))

Marc

Jan 31 '06 #2
Follow up: it also looks like Enum.IsDefined(typeof(Title), theString) might
do what you want.

Annoyingly, .Net 2 doesn't (as far as I know) provide a type-safe Enum
helper; but if you use enums a lot you might find the following saves a few
casts and "typeof"s; not a massive saving, but can be handy; e.g.

MyEnum[] values = Enum<MyEnum>.GetValues();
or
MyEnum value;
Enum<MyEnum>.TryParse("SomeText", out value);
or
bool defined = Enum<MyEnum>.IsDefined(theString);

etc

Marc

public static class Enum<T> {
public static bool TryParse(string name, out T value) {
return TryParse(name, out value, false);
}
public static bool TryParse(string name, out T value, bool
ignoreCase) {
try {
value = (T) Enum.Parse(typeof(T), name, ignoreCase);
return true;
} catch { // one of the rare cases where this is broadly
acceptable; could test IsDefined first perhaps?
value = default(T);
return false;
}
}
public static T Parse(string name) {
return Parse(name, false);
}
public static T Parse(string name, bool ignoreCase) {
return (T)Enum.Parse(typeof(T), name, ignoreCase);
}
public static string[] GetNames() {
return Enum.GetNames(typeof(T));
}
public static T[] GetValues() {
return (T[])Enum.GetValues(typeof(T));
}
public static string Format(T value, string format) {
return Enum.Format(typeof(T), value, format);
}
public static bool IsDefined(object value) {
return Enum.IsDefined(typeof(T), value);
}
public static Type GetUnderlyingType() {
return Enum.GetUnderlyingType(typeof(T));
}
}
Jan 31 '06 #3

"Wolf" <ja********@citadel.co.za> wrote in message
news:11*********************@g44g2000cwa.googlegro ups.com...
Hi all

Who can Help me with this one?
if I have this Enums:
#region Title
public enum Title: short
{
NA = 0,
Mr = 2,
Adv = 3,
Brig = 4,
Dr = 5,
Genl = 6,
Prof = 7,
Miss = 8,
Mrs = 9,
Adm = 10,
Rev = 11,
Ms = 12,
}
Now I want to take the textbox.text and loop through the enums(Not the
value) to check if it exist in my enums
Something like this:

Public bool DoesTitle Exist
{
blnValid = false
For each enum
{
if (textbox.text == enum.name(Example: "MR"))
return true
break
}

return blnValid ;

}
}
Thanks a mill for those who can help


1) See System.Enum.GetNames()

2) A simpler solution with a nicer UI is to populate a combobox with
Enum.GetNames then use Enum.Parse on the selection.

3) I do it all the time but it is neither internationalizable nor easily
extendable: the title should really be a string rather than an enum because
you will (probably) never write a conditional statement based on the value.

Jan 31 '06 #4
Thank you very much for your input, I eventually figure it out and I
must say Enum.Parse is powerfull and nice to use
I just have a last question:

I want to retrieve the ID of _title I send in if it was found:

Like - int EnumID = (int)_title

How do I do this?
_title = "Mr";

Common.Title _myEnum = (Common.Title)Enum.Parse(typeof(Common.Title),
_title, true);

bool pblnIsDefined =
Enum.IsDefined(typeof(Citadel.Horizon.Common.Enums .Common.Title),
_myEnum);
if (pblnIsDefined)
{
contact.Title = currentContact.Title;
contact.PartyStampDate = DateTime.Now;
IOUtility.WriteContact(contact);
break;
}
else
{
string _validhorizonID3 =
currentContact.UserProperties["HorizonID"].Value.ToString();
MessageBox.Show("There is no such title on system, please type a
valid title for Client:" + _validhorizonID3 + ".");

}

Jan 31 '06 #5
What do you mean by ID?

The strongly-typed value (from your bespoke enum), or the index of the
specific enum in the set of enums?

If the former, then you already have it: just cast to Title
If the latter, hmm... I'm not 100% sure that position is guaranteed to be
preserved (vs. the source code), but assuming you have used Enum.GetValues
to list them you could presumably loop through them again without issues;
the following extension to Enum<T> would do the job:

public static int GetIndex(T value) {
int index = 0;
foreach (T item in GetValues()) {
if (Enum.Equals(item,value))
return index;
index++;
}
throw new ArgumentOutOfRangeException();
}

If you are talking about something else (position in a specific drop-down or
similar) then you'd need to use methods appropriate to your implementation.

Marc
Jan 31 '06 #6
Hi,

"Wolf" <ja********@citadel.co.za> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Thank you very much for your input, I eventually figure it out and I
must say Enum.Parse is powerfull and nice to use
I just have a last question:


If I were you I would go with Nick's suggestion and use a combobox instead
of a textbox

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Jan 31 '06 #7
I cant go reallly with Nicks suggestion, cause I am using Outlook's
events.

For instance, our system has a set of titles.Our project creates
contacts in outlook.So now when you change the contact's title in
outlook, it updates our system(DB) if the title in outlook exists in
our set titles in our system.

But I figure all out, but of course I couldnt do it without your
help.Thanks alot

Feb 1 '06 #8

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

Similar topics

13
by: SpaceCowboy | last post by:
I recently got into a discussion with a co-worker about using enums across a dll interface. He wanted to use chars instead, argueing that depending on compiler settings the size of an enum could...
2
by: Faisal | last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't...
27
by: Mark A. Gibbs | last post by:
i have been toying with the idea of making my enums smarter - ie, more in line with the rest of the language. i haven't tested it yet, but what i came up with is a template like this: template...
2
by: SpotNet | last post by:
Hello CSharpies, Can Enums in C# be UInt32 Types, and not just Int32 Types. I have a lot of constant declarations that are UInt32 that I want to put in Enums to ease the use of Intellisence. I...
4
by: Martin Pritchard | last post by:
Hi, I'm working on a project that historically contains around 40 enums. In the database various fields refer to the int values of these enums, but of course ref integrity is not enofrced and...
2
by: Simon Elliott | last post by:
I have some legacy C++ code which requires some enums to be 1 or 2 bytes in size. I'd ideally like to be able to specify that a few carefully selected enums are a particular size. By default,...
8
by: CK | last post by:
Hi All, Good morning. I had a quick question. I have a public Enum. During page load I want to loop thru the Enum and put those as items in an asp:dropdownList. Does anyone have any sample code to...
11
by: Marc Gravell | last post by:
This one stumped me while refactoring some code to use generics... Suppose I declare an enum MyEnum {...} Is there a good reason why MyEnum doesn't implement IEquatable<MyEnum> ? Of course,...
3
by: mrsouthg | last post by:
Hi, I am fairly new to c# .net language and have been using a set of code I was given to learn from. I have found a suitable part which I would like to change, I am however finding it a big hurdle...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.