Archive

Archive for May, 2012

Page Method And Life Cycle

Categories: ASP.Net

Add & Get Attribute Value

public enum OrderDataInputStatus
{
[Description(“Invalid Amount For InvoiceType”)]
InvalidAmountForInvoiceType = 512
}

private string GetDescription(Enum enumValue)
{
Type type = enumValue.GetType();
string selectedOptionName = Enum.GetName(type, enumValue);
if (selectedOptionName != null)
{
FieldInfo field = type.GetField(selectedOptionName);
if (field != null)
{
DescriptionAttribute attributeDesc =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;

if (attributeDesc != null)
{
return attributeDesc.Description;
}
}
}

return null;

}

public static T GetValueFromDescription<T>(string description)
{
var enumType = typeof(T);
if (!enumType.IsEnum) throw new InvalidOperationException();
foreach (var field in enumType.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException(“Not found.”, “description”);
}

Categories: C#