Geeks With Blogs

News
Jason Coyne Jason Coyne's blog

I found a post on Abhinaba's Blog talking about a cool way to override ToString on an enum to get human readable values out of it. I like the atributes, but have my own solution below.

 In the past I have used a function that converts the enum strings to human strings.  This code relies on the developer using good naming standards for the enum values. But if you can't rely on that, you couldn't rely on them to put in the attribute values either, so I call it a wash.

I have another function that you can pass an enum type, and it will populate a drop down list from the enum, using the int value for the list values, and the text description (passed through this function) for the text value.

I may try to unify the two solutions, so that the attributes are provided, but the strings are generated automatically.

public static string FixEnumString(string s)

{

string output = "";

StringBuilder sb = new StringBuilder(s.Length);

foreach (char c in s)

{

if (sb.Length != 0)

{

if (c.ToString()!=c.ToString().ToLower())

sb.Append(" ");

}

sb.Append(c);

}

output = sb.ToString();

output = output.Replace("I D", "ID");

output = output.Replace("_"," ");

output = output.Replace(" ", " ");

 

return output;

}

 

 

public static void PopulateDropDownListBoxFromEnum(DropDownList list, System.Type enumType)

{

list.Items.Clear();

foreach (object currentEnumValueObject in System.Enum.GetValues(enumType))

{

int currentEnumValue = (int) currentEnumValueObject;

string currentEnumText= currentEnumValueObject.ToString();

currentEnumText = FixEnumString(currentEnumText);

//currentEnumText = Translator.TranslateText(currentEnumText);

list.Items.Add(new ListItem(currentEnumText, currentEnumValue.ToString()));

}

}

 

Posted on Thursday, October 20, 2005 5:38 AM Programming , c# | Back to top


Comments on this post: Getting human readable values out of an enum.

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Jason Coyne | Powered by: GeeksWithBlogs.net