c# - Get an enumerated field from a string -
bit of strange 1 this. please forgive semi-pseudo code below. have list of enumerated values. let's instance, so:
public enum types { foo = 1, bar = 2, baz = 3 }
which become, respectfully, in code:
types.foo types.bar types.baz
now have drop down list contains 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 sake of completeness:
dropdownlistid.items.add(li1); dropdownlistid.items.add(li2); dropdownlistid.items.add(li3);
hope still me. want on autopostback take string "foo" , convert types.foo - without using switch (as enumerated values generated database , may change).
i hope makes sense? idea start?
sure:
types t; if(enum.tryparse(yourstring, out t)) // yourstring "foo", example { // use t } else { // yourstring not contain valid types value }
there's overload takes boolean allows specify case insensitiveness: http://msdn.microsoft.com/en-us/library/dd991317.aspx
enum.tryparse
new in .net 4. if you're stuck on previous version, you'll have use non-typesafe enum.parse
method (which throws exception in case of conversion failure, instead of returning false
), so:
try { types t = (types)enum.parse(typeof(types), yourstring); // use t } catch(argumentexception) { // yourstring not contain valid types value }
enum.parse
has overload case insensitiveness.
Comments
Post a Comment