How to display enum value as V1.0, V2.0, V3.0 in C# ?
enum value
{
V1.0,
V2.0,
V3.0
}
How to display enum value as V1.0, V2.0, V3.0 in C# ?
enum value
{
V1.0,
V2.0,
V3.0
}
A possible solution would be the use of the DescriptionAttribute:
enum value
{
[Description("V1.0")]
V1_0,
[Description("V2.0")]
V2_0,
[Description("V3.0")]
V3_0
}
You cannot use .
in identifier names.
See the C# Specification on Identifiers
The best you can do would be something like:
enum value
{
V1dot0,
V2dot0,
V3dot0
}
or
enum value
{
V10,
V20,
V30
}
or
enum value
{
V1_0,
V2_0,
V3_0
}
or use Description
attribute like Koen suggests.
You have to declare your enum without dots e.g.
public enum value {
V1,
V2,
V3
}
but you can implement extension method to represent enum values:
public static class valueExtensions {
public static String ToReport(this value item) {
switch (item) {
case value.V1:
return "V1.0";
case value.V2:
return "V2.0";
case value.V3:
return "V3.0";
default:
return "?";
}
}
}
...
value data = value.V1;
String result = data.ToReport(); // <- "V1.0"
you can also use readonly
array :
public readonly string[] value={"V1.0","V2.0","V3.0"};
The only workaround I know to do this is via descriptions like described here
Write a static method to display it, or encapsulate it in a class and override ToString method.
ToString(enumValue eValue){
switch (eValue) {
case V10:
return "V1.0";
break;
case V20:
return "V2.0";
break;
}
}
You cannot assign string values to an enum however you can assign using attributes. You have to associate a numeric value with a description
using System.ComponentModel;
namespace myCompany.MyProject.BO {
public enum SampleTypes
{
// Default
[Description("- None -")]
None=0,
[Description("My type 1")]
V1=1,
[Description("My type 2")]
V2=2,
[Description("My type 3")]
V3=3
} }
Then you can define helper methods to get either the description or a key,value pair for binding to a dropdown list
public static string GetDescription(System.Enum value)
{
FieldInfo FieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])FieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
public static List<KeyValuePair<string, string>> GetValuesAndDescription(System.Type enumType)
{
List<KeyValuePair<string, string>> kvPairList = new List<KeyValuePair<string, string>>();
foreach (System.Enum enumValue in System.Enum.GetValues(enumType))
{
kvPairList.Add(new KeyValuePair<string, string>(enumValue.ToString(), GetDescription(enumValue)));
}
return kvPairList;
}
You can bind your dropdownlists this way
Helpers.GetValuesAndDescription(typeof(YourEnumName));
YourDropDown.DataValueField = "Key";
YourDropDown.DataTextField = "Value";
YourDropDown.DataBind();`