How do I convert an Enum value to a String?

How do I convert an Enum value to a String?

This article shows how to convert an enum value to a string value.

I have an enum SortFilter, which looks like following:

public enum SortFilter

{

      FirstName,

      LastName,

      Age,

      Experience

}

Now, let's say I want to display the string value of enum in some control. For that, I will have to convert Enum value to string. For example, I want to add all enum string values to a DropDownList. The following code loops through the enumeration and adds string values to it. Here SortByList is DropDownList.

SortByList.Items.Clear();

// Conversion from Enum to String

foreach (string item in Enum.GetNames(typeof(ArrayListBinding.SortFilter)))

{

      SortByList.Items.Add(item);
}    

This code converts an enum to string:

string name= Enum.GetName(typeof(ArrayListBinding.SortFilter), SortFilter.FirstName);

Now let's say, you have an enum string value say, "FirstName" and now you want to convert it to Enum value. The following code converts from a string to enum value, where Developer.SortingBy is of type SortFilter enumeration:

// Conversion from String to Enum

Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "FirstName");  


From:
http://www.c-sharpcorner.com/UploadFile/mahesh/EnumToString10212005144136PM/EnumToString.aspx?ArticleID=125bc152-e7f6-4322-8c3f-c871f5bd1a6f

posted @ 2005-11-29 15:24  jhtchina  阅读(614)  评论(0编辑  收藏  举报