473,597 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(Examp le: "MR"))
return true
break
}

return blnValid ;

}
}
Thanks a mill for those who can help

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

Enum.Parse(type of(Title),theTe xt)

However, to enumerate, just use

Enum.GetNames(t ypeof(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>.Ge tValues();
or
MyEnum value;
Enum<MyEnum>.Tr yParse("SomeTex t", out value);
or
bool defined = Enum<MyEnum>.Is Defined(theStri ng);

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(type of(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(t ypeof(T), name, ignoreCase);
}
public static string[] GetNames() {
return Enum.GetNames(t ypeof(T));
}
public static T[] GetValues() {
return (T[])Enum.GetValues (typeof(T));
}
public static string Format(T value, string format) {
return Enum.Format(typ eof(T), value, format);
}
public static bool IsDefined(objec t value) {
return Enum.IsDefined( typeof(T), value);
}
public static Type GetUnderlyingTy pe() {
return Enum.GetUnderly ingType(typeof( T));
}
}
Jan 31 '06 #3

"Wolf" <ja********@cit adel.co.za> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.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(Examp le: "MR"))
return true
break
}

return blnValid ;

}
}
Thanks a mill for those who can help


1) See System.Enum.Get Names()

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 internationaliz able 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)E num.Parse(typeo f(Common.Title) ,
_title, true);

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

}

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(it em,value))
return index;
index++;
}
throw new ArgumentOutOfRa ngeException();
}

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********@cit adel.co.za> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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
9539
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 change and lead to memory corruption. I didn't see how this was possible. He claims that if a dll built for a program is built with different compiler settings than the launcher program, the enum size could change. The only way I could figure...
2
2066
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 seem to find an appropriate Reflection method to access Enums within a class I would like to loop through the Enums in the 'Foo' Class retrieve the Enums 'Car' and 'House Public Class Fo Public Enum Ca For Chevrole Toyot
27
2719
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 <typename Enum> class smart_enum { public: typedef Enum enum_type;
2
1790
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 have them in structs for now, I thought I'd ask. Would IntPtr Enums push the bounds of a stupid question? Regarding a post a bit further down by Tom; ' What would you like to change in C# and .NET?'
4
5584
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 when looking at the db we can't tell what the value in a field represents. The other problem is that our enums are currently all stored in a single class, which means that because of no visibility constraints the enums are often used out of context...
2
2876
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, g++ seems to create enums of 4 bytes in length, unless I use the -fshort-enums option. I don't much want to use this all or nothing approach in case it breaks library code etc, and there's no guarantee that other compilers have a comparable...
8
1984
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 do this? Like a foreach loop. Thanks for any help, CK
11
12471
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, I can cast a MyEnum instance down to the int / short whatever (since int implements IEquatable<int>), but I don't like doing that, as it feels a bit messy, and I am then propegating the things that know what the base represenation is...
3
2214
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 to get going. Console.WriteLine("GetMeetingsOnDate"); var getMeetingsOnDateResp = timeFormApi.GetMeetingsOnDate(DateTime.Now); Console.WriteLine("GetRaceList"); var getRaceListresp = timeFormApi.GetRaceList
0
7887
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8274
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8381
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8036
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8259
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6695
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5434
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3930
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1241
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.