Friday, April 25, 2008

enum - most useful functions

When i am doing .NET programming, many times i have get use of common tasks required related to ‘enum’. Then i taught of writing some common functions related to enum reading, parsing, iterating enum etc. Here we go …

What is enum: enumuration is comprised of a number of named constants.

Creating Enumuration :
public enum UIType
{
None,
Label,
DropDown,
TextBox,
CheckBox,
ListBox,
DateTimePicker
}

Convert Enumuration Item to string :
string itemValue = UIType.CheckBox.ToString();

Convert string to Enumuration instance:
returnValue = (UIType)Enum.Parse(typeof(UIType), str, true);

Note:
// While parsing enum it throws an ArgumentException if the string is found not to be one of the members of the enum. you must handle it.

Iterating Enum and reading data from Enum:
foreach
(string s in Enum.GetNames( typeof(UIType)))
dropdownlist1.Items.Add(s);

Convert integer to Enum instance:
UIType chkbox=(UIType)Enum.ToObject(typeof(UIType), (int)UIType.CheckBox);

 

Posted by at 10:58:42
Comments

Leave a Reply