Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch value of enum?

Tags:

c#

.net

asp.net

I have defined an enum like

public Enum CompanyQuarters
{
     First=1,
     Second=2,
     Third=3,
     Fourth=4
}

I bind them to dropdown list like

ddlCompQuarter.DataSource = Enum.GetNames(typeof(CompanyQuarters));
ddlCompQuarter.DataBind();

Now I want to fetch the dropdownlist selected value For e.g for selection 'second' I like to fetch 2 ?

This does not work

 int selectedVal = int.Parse(ddlCompQuarter.SelectedValue.ToString());
like image 853
Zo Has Avatar asked Nov 30 '22 06:11

Zo Has


1 Answers

ActiveQuarters value = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters),ddlCompQuarter.SelectedValue.ToString());

or if you are using Dot Net Framework 4 or greater, see Enum.TryParse

ActiveQuarters value;
Enum.TryParse<ActiveQuarters>(ddlCompQuarter.SelectedValue.ToString(), out value);
like image 55
sga101 Avatar answered Dec 05 '22 17:12

sga101