John Haigh's Blog

  Home  |   Contact  |   Syndication    |   Login
  8 Posts | 0 Stories | 8 Comments | 0 Trackbacks

News

Archives

Post Categories

Links

Projects


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
{
   Folder,
   File
}
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

Feedback

# re: Convert a string value to an Enum 1/23/2012 11:45 PM Joe Zanotti
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


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: