Get an enumerated field from a string
Bit of a strange one this. Please forgive the semi-pseudo code below. I have a list of enumerated values. Let's say for instance, like so:
public enum Types
{
foo = 1,
bar = 2,
baz = 3
}
Which would become, respectfully, in the code:
Types.foo
Types.bar
Types.baz
Now I have a drop down list that contains the following List Items:
var li1 = new ListItem() { Key = "foo" Value = "Actual Representation of Foo" }
var li2 = new ListItem() { Key = "bar" Value = "Actual Representation of Bar" }
var li3 = new ListItem() { Key = "baz" Value = "Actual Representation of Baz" }
for the sake of complet开发者_如何学编程eness:
dropDownListId.Items.Add(li1); dropDownListId.Items.Add(li2); dropDownListId.Items.Add(li3);
Hope that everyone is still with me. What I want to do is to on the Autopostback is take the string "foo" and convert that to Types.foo - without using a switch (as the enumerated values are generated from a database and may change).
I hope that makes sense? Any idea where to even start?
Sure:
Types t;
if(Enum.TryParse(yourString, out t)) // yourString is "foo", for example
{
// use t
}
else
{
// yourString does not contain a valid Types value
}
There's also an overload that takes a boolean that allows you to specify case insensitiveness: http://msdn.microsoft.com/en-us/library/dd991317.aspx
Enum.TryParse
is new in .NET 4. If you're stuck on a previous version, you'll have to use the non-typesafe Enum.Parse
method (which throws an exception in case of conversion failure, instead of returning false
), like so:
try
{
Types t = (Types)Enum.Parse(typeof(Types), yourString);
// use t
}
catch(ArgumentException)
{
// yourString does not contain a valid Types value
}
Enum.Parse
also has an overload for case insensitiveness.
So, you want: Enum.Parse(typeof(Types), postbackValue)
or did I miss something?
If I understood correctly, you can do:
Types fooEnum = Enum.Parse(typeof(Types), "foo");
See: http://msdn.microsoft.com/en-us/library/essfb559.aspx
精彩评论