Friday, March 2, 2012

.NET: using enum to populate combo box, and parsing the selected value to the enum

I was creating a simple tool and I wanted to have all my drop downs from Enums, and I wanted to get the selected value

I did it like below

The Enum

public enum Status { Active = 0, Canceled = 3 };

Setting the drop down values from it

cbStatus.DataSource = Enum.GetValues(typeof(Status));

Getting the enum from the selected item

Status status; Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status);