How to fetch value of enum? - c#

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());

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);

Here I am showing you the best way to use enum:
public enum enumVIPBusinessPlanPaymentType {
[Description("Monthly")]
Monthly = 1,
[Description("Paid In Full (PIF)")]
PaidInFull = 2,
[Description("Barter")]
Barter = 3 }
and create a EnumHelper.cs class to read its value or description
public static Int32 GetIntValue(Enum en)
{
Type type = en.GetType();
return TemplateControlExtension.GetInt32(null, en);
}
public static string GetStringNameFromValue(Enum en)
{
Type type = en.GetType();
MemberInfo[] info = type.GetMember(en.ToString());
if (info != null && info.Length > 0)
{
object[] attrs = info[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return TemplateControlExtension.GetString(null, en);
}
I hope it will like you

ActiveQuarters typedValue = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters),
ddlCompQuarter.SelectedValue);
// If you need numeric value
int numericValue = (int)typedValue;

CompanyQuarters comp= (CompanyQuarters)Enum.Parse(ddlCompQuarter.SelectedValue);

You can use Enum.Parse
var val = (int)(ActiveQuarters)Enum.Parse(typeof(ActiveQuarters),
ddlCompQuarter.SelectedValue.ToString());
Also I think your code has problem, you defined ActiveQuarters enum and you bind CompanyQuarters!.

You have to reverse the way you got the names in there.
http://blogs.msdn.com/b/tims/archive/2004/04/02/106310.aspx

you need to use Enum.Parse and then you can get your enum from ComboBox

You have to set text and value property at time of binding the drop down.
For value field you can use
Enum.GetValues(typeof(EnumProvider.CompanyQuarters))

Related

Error: Unable to cast object of type 'System.Int32' to type 'System.String'

I have finish perfectly coding Register Page, Login and now the UpdateCustomer page has errors - Background info : I'm using Microsoft Access as data source
LabelState.Text = (string)Session["sState"];
LabelPostalCode.Text = (string)Session["sPostalCode"];
LabelContactNumber.Text = (string)Session["sContactNumber"];
LabelEmail.Text = (string)Session["sEmail"];
LabelPassword.Text = (string)Session["sPassword"];
Everything here is fine except LabelContactNumber.Text = (string)Session["sContactNumber"].
I believe it is because only ContactNumber in Access is set as Int the rest is Text therefore there's no error when I use (string).
Problem : it is failing because you are assigning the Integer type into String.
here you need to use explicit conversion to convert the Integer type into String type.
Solution : if you want to check wether contact number can be parsed to int or not before assigning it into TextBox use TryParse method
int contact;
if(int.TryParse(Session["sContactNumber"],out contact))
LabelContactNumber.Text = contact.ToString();
else
LabelContactNumber.Text = "Invalid Contact!";
LabelContactNumber.Text = (Session["sContactNumber"] != null)
? Session["sContactNumber"].ToString()
: string.Empty //or whatever default value your want;
int contactNumber = -1;
if( int.TryParse( Session[ "sContactNumber" ], out contactNumber ) == false )
{
LastContactNumber = "N/A";
}
else
{
LastContactNumber = contactNumber.ToString( );
}

Where should I put take the string of last two chars

Hi I need to narrow down the search string to allow users to put some flags at the end of search like "/A" or "/W". This is wpf and MVVM. I tried to put it in the property but it looks like it doesn't work. Where should I put it if I can't put it in the property.
public NavDataType Type
{
get
{
return _type;
}
set
{
if (_type.ToString().Substring(_type.ToString().Length - 2, 2) == "/A")
_type = NavDataType.Airport;
if (_type.ToString().Substring(_type.ToString().Length - 2, 2) == "/W")
_type = NavDataType.Waypoint;
if (_type.ToString().Substring(_type.ToString().Length - 2, 2) == "/N")
_type = NavDataType.Navaid;
SetProperty(ref _type, value, "Type");
}
}
if (_type.ToString().Substring(_type.ToString().Length - 2, 2) == "/N")
_type = NavDataType.Navaid;
SetProperty(ref _type, value, "Type");
the problem is that you're setting _type in the if statements (works correcty), but then the SetProperty call is overwriting that with whatever value was when it got passed in.

Why won't my drop down default to the given value?

I've created a SelectList from a enum. The enum has a description, and the int value is being set to the value I want to store in the database.
The problem is, the default (BLANK) I set on construction isn't being used.
This is my enum:
public enum Stage
{
[Description("")]
BLANK = -99,
[Description("No Data")]
NoData = 9999,
[Description("Nil")]
Nil = 0,
[Description("Action")]
SAction = 1,
[Description("Action Plus")]
SActionPlus = 2,
[Description("Full")]
Full = 3
}
I create it in my controller:
private static IEnumerable<SelectListItem> GenerateSenStageList()
{
var values = from Stage e in Enum.GetValues(typeof(Stage))
select new { ID = (int)e, Name = e.ToDescription() };
return new SelectList(values, "Id", "Name", (int)Stage.BLANK);
}
Where I thought the final parameter set the selected item.
I assign it as ViewData, and access it like:
<%= Html.DropDownList("Stage", (IEnumerable<SelectListItem>)ViewData["StageList"])%>
However, Nil is always the selected value.
What am I missing here??
Thanks!
The last parameter does determine the selected value. However, you are passing a Stage enumerated value as the last parameter, while the actual elements of your list are made up of an ID value and a Stage value. To make this work, you have to pass it the actual object from values with a Stage value of BLANK.
Iainie,
Using your code, i managed to get this working first time. here's my amended code (using the accountcontroller for testing) [using .net 3.5]:
// from account controller - put the enum, etc in there for brevity
public enum Stage
{
[Description("")]
BLANK = -99,
[Description("No Data")]
NoData = 9999,
[Description("Nil")]
Nil = 0,
[Description("Action")]
SAction = 1,
[Description("Action Plus")]
SActionPlus = 2,
[Description("Full")]
Full = 3
}
public static IEnumerable<SelectListItem> GenerateSenStageList()
{
var values = from Stage e in Enum.GetValues(typeof(Stage))
select new { ID = (int)e, Name = e.ToDescription() };
var sellist= new SelectList(values, "Id", "Name", (int)Stage.BLANK);
return sellist;
}
public virtual ActionResult LogOn()
{
var res = GenerateSenStageList();
ViewData["StageList"] = res;
return View();
}
// the ToDescription() extension method
public static class Extn
{
public static string ToDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
var attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
// then in the LogOn view:
<%= Html.DropDownList("Stage", (IEnumerable<SelectListItem>)ViewData["StageList"])%>
this all works exactly as you'd hoped for, so I'm wondering if your invocation from the view is somehow getting a bit fuddled. try my example above and see if there are any subtle differences in the selectlist generated code etc.
Just a guess, but:
You cast the ViewData["StageList"] to IEnumerable<SelectListItem>. That enumerable may be the SelectList that you created in the Controller, but it does not have the SelectedValue property.
Maybe it works if you cast ViewData["StageList"] to SelectList instead?
<%= Html.DropDownList("Stage", (SelectList)ViewData["StageList"])%>
In this case using the interface may be the wrong thing, because you actually need the information provided by the SelectList object.
#Ken Wayne VanderLinde is right. If you are using C# 4.0, then you can do this to populate the selected value:
private static IEnumerable<SelectListItem> GenerateSenStageList()
{
var values = from Stage e in Enum.GetValues(typeof(Stage))
select new { ID = (int)e, Name = e.ToDescription() };
return new SelectList(values, "Id", "Name", values.Cast<dynamic>().Where(x => (x.ID == (int)Stage.BLANK)));
}

Using strings instead of enums?

Is it common place to use a string for comparison as opposed to an enum?
I am aware about your context, but as a first step you can just refactor this way:
Step 1
if (typeOfObject == "UAV")
{
DoSomeWork(_stkObjectRootToIsolateForUavs);
}
else if (typeOfObject == "Entity")
{
DoSomeWork(_stkObjectRootToIsolateForEntities);
}
private void DoSomeWork(IAgStkObject agStkObject)
{
IAgStkObject stkObject = agStkObject.CurrentScenario.Children[stkObjectName];
IAgDataProviderGroup group = (IAgDataProviderGroup)stkUavObject.DataProviders["Heading"];
IAgDataProvider provider = (IAgDataProvider)group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar)provider).ExecSingle(_stkObjectRootToIsolateForUavs.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double)result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double)result.DataSets[4].GetValues().GetValue(0);
}
Then consider replasing if's with switch:
Step 2
switch (typeOfObject)
{
case "UAV":
DoSomeWork(_stkObjectRootToIsolateForUavs);
break;
case "Entity":
DoSomeWork(_stkObjectRootToIsolateForEntities);
break;
default:
throw new NotImplementedException():
}
This can be even better when using enums.
At the very least, the strings should be declared as constants (or perhaps readonly fields) somewhere, instead of spread out through the code. However, this looks like the schoolbook example for when to use an enum.
public enum ObjectType
{
UAV,
Entity,
// and so on
}
To add to #Restuta's answer, I'd use a
IDictionary<MyEnumifiedString, Action<IAgStkObject>>
to get rid of that if.
I'd agree with #Frederik that this seems a perfect case for using enums, but it could be that the only thing you can get out of the application is a string. In which case your example is perfectly OK.
Oh yes - and make sure you have the string constants defined in one place, preferably a config file so that if they change the other application you don't have to recompile yours.
Regarding your first question I will always use a defined type to store the strings simply to have one location for change if needed.
So for your example i would have the following
public sealed class RootTypes
{
public const string Entity = "entity";
public const string UAV = "uav";
}
Your code then updates to this
typeOfObject = typeOfObject.ToLower();
if (typeOfObject == RootTypes.UAV)
{
stkUavObject = _stkObjectRootToIsolateForUavs.CurrentScenario.Children[stkObjectName];
var group = (IAgDataProviderGroup) stkUavObject.DataProviders["Heading"];
var provider = (IAgDataProvider) group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar) provider).ExecSingle(_stkObjectRootToIsolateForUavs.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double) result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double) result.DataSets[4].GetValues().GetValue(0);
}
else if (typeOfObject == RootTypes.Entity)
{
IAgStkObject stkEntityObject = _stkObjectRootToIsolateForEntities.CurrentScenario.Children[stkObjectName];
var group = (IAgDataProviderGroup) stkEntityObject.DataProviders["Heading"];
var provider = (IAgDataProvider) group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar) provider).ExecSingle(_stkObjectRootToIsolateForEntities.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double) result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double) result.DataSets[4].GetValues().GetValue(0);
}
The issue of code redundancy has been anserwed by Restuta
Use enums with bit flags:
[Flags]
public enum MyFlags
{
SomeFlag = 0x1, // 001
OtherFlag = 0x2,// 010
ThirdFlag = 0x4 // 100
}
var firstObject = MyFlags.SomeFlag;
var secondObject = MyFlags.SomeFlag | MyFlags.OtherFlag;
if(((int)secondObject & MyFlags.SomeFlag) != 0)
{
// true
}
if(((int)secondObject & MyFlags.OtherFlag) != 0)
{
// true
}
if(((int)firstObject & MyFlags.SomeFlag) != 0)
{
// true
}
if(((int)firstObject & MyFlags.OtherFlag) != 0)
{
// false
}
This article would be helpful.

How can I add some Enum values to a combobox

In the following example I would like to add flavours that start with "APPLE" to a ComboBox on a form. When the enums have unique values it works fine; however, in my example two enums PINEAPPLE_PEACH and APPLE_ORANGE both have a value of 1 and this messes up the results.
Is it erroneous to have two enums with the same value and, if so, how can I change my code to get consistent results?
public enum Flavour
{
APPLE_PEACH = 0,
PINEAPPLE_PEACH = 1,
APPLE_ORANGE = 1,
APPLE_BANANA = 3,
PINEAPPLE_GRAPE = 4
}
private void AddFlavours()
{
foreach (Flavour flavour in Enum.GetValues(typeof(Flavour)))
{
string flavourName = Enum.GetName(typeof(Flavour), flavour);
if (flavourName.StartsWith("APPLE"))
{
myComboBox.Items.Add(flavour);
}
}
}
With Linq, you may use this:
foreach (string flavourName in Enum.GetNames(typeof(Flavour)).Where(s => s.StartsWith("APPLE")))
{
myComboBox.Items.Add(flavourName);
}
You can use Enum.GetNames instead of GetValues. It would be something like this (not tested):
foreach (string flavourName in Enum.GetNames(typeof(Flavour)))
{
if (flavourName.StartsWith("APPLE"))
{
myComboBox.Items.Add(Enum.Parse(typeof(flavour), flavourName));
}
}

Categories