I'm using MarkupConverters in WPF to parse from enum values to human readable strings.
Is there a way for ASP.NET and the ASP.NET GridView or DevExpress ASPxGridView to do the same as in WPF?
Something like that (from WPF) in ASP.NET:
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
namespace Converters
{
public class PriorityToStringConverter
: MarkupExtension, IValueConverter
{
public PriorityToStringConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is byte)
{
switch ((byte)value)
{
case 0:
return "Very high";
case 1:
return "High";
case 2:
return "Normal";
case 3:
return "Low";
case 4:
return "Very low";
default:
return value;
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
Well, ASP.Net doesn't have built-in converters such as WPF unfortunately. What you can do is make your own custom converter to be used on an ASP.Net GridView.
Here is a short example:
Start by adding a System.ComponentModel.Description
to your enum values like this:
public enum MyEnum
{
[Description("Desc for A")]
MyA = 0,
[Description("Desc for X")]
MyX,
[Description("Desc for Y")]
MyY
}
For the demo, my data model is a list of these:
public class MyData
{
public string Name { get; set; }
public MyEnum Value {get; set;}
}
Now, in your page create the following function which extracts the description given a specific enum value:
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
Usage in a GridView:
<Columns>
<asp:TemplateField HeaderText="Value" SortExpression="Value">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# GetEnumDescription((Enum)Eval("Value")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
What I basically do is after using Eval
to get the Value
property for a specific row, I call the function I created to extract the description, give the Enum value and that is what I display in the label.