Geeks With Blogs
John Haigh's Blog

To convert a string value to an Enum, which may be required after retrieving data from an SqlDataReader. To give more context an Order object is created/returned from a static method GetOrderByOrderId and the Order object has a property OrderStatus that is an Enum which needs to be converted as it is stored as a string variable in SQL Server database table.

Example Enum OrderStatus:

public Enum ArtifactType
Order Class to represent our Order Object:

public class Order
   public int Orderid { get; set; }
   public OrderStatus OrderStatus { get; set; }

public static Order GetOrderByOrderId(int Orderid)
     SqlDataReader r = sqlComm.ExecuteReader();
  while ( r.Read() )

     Order o = new Order();
     string orderStatus = (string)reader["OrderStatus"];
     OrderStatus os = (OrderStatus) Enum.Parse(typeof(OrderStatus), orderStatus);
     o.OrderStatus = os;
   return o;

An Order object is created, then assign the OrderStatus value from the order table and assign this to a string. Next the we convert this string value "orderStatus" to the OrderStatus enum and assign to the Order object OrderStatus property.
Posted on Saturday, February 28, 2009 5:10 PM Base Class Library | Back to top

Comments on this post: Convert a string value to an Enum

# re: Convert a string value to an Enum
Requesting Gravatar...
I haven't come across such error. However, thanks to your post, I will have the knowledge on how to deal with this issue. - Joe Zanotti
Left by Joe Zanotti on Jan 23, 2012 11:45 PM

Your comment:
 (will show your gravatar)

Copyright © John Haigh | Powered by: