enum to comboBox
from https://stackoverflow.com/questions/3063320/combobox-adding-text-and-value-to-an-item-no-binding-source
Dictionary<int, string> test = new Dictionary<int, string>();
foreach (Station station in (Station[])Enum.GetValues(typeof(Station)))
{
test.Add((int)station, EntityUtil.GetEnumDescription(station));
}
comboBoxOCV.DataSource = new BindingSource(test, null);
comboBoxOCV.DisplayMember = "Value";
comboBoxOCV.ValueMember = "Key";
public enum Station
{
[Description("All")]
All,
[Description("OCV1")]
OCV1,
[Description("OCV2")]
OCV2,
}
public static string GetEnumDescription(object value)
{
string description = null;
try
{
if (value != null)
{
string strValue = value.ToString();
if (0 < strValue.Length)
{
FieldInfo fi = value.GetType().GetField(strValue);
Attribute attr = Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
if (attr != null)
{
DescriptionAttribute descAttr = (DescriptionAttribute)attr;
description = descAttr.Description;
}
}
}
}
catch
{
description = value.ToString();
}
return description;
}
Dictionary<int, string> test = new Dictionary<int, string>();
foreach (Station station in (Station[])Enum.GetValues(typeof(Station)))
{
test.Add((int)station, EntityUtil.GetEnumDescription(station));
}
comboBoxOCV.DataSource = new BindingSource(test, null);
comboBoxOCV.DisplayMember = "Value";
comboBoxOCV.ValueMember = "Key";
public enum Station
{
[Description("All")]
All,
[Description("OCV1")]
OCV1,
[Description("OCV2")]
OCV2,
}
public static string GetEnumDescription(object value)
{
string description = null;
try
{
if (value != null)
{
string strValue = value.ToString();
if (0 < strValue.Length)
{
FieldInfo fi = value.GetType().GetField(strValue);
Attribute attr = Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
if (attr != null)
{
DescriptionAttribute descAttr = (DescriptionAttribute)attr;
description = descAttr.Description;
}
}
}
}
catch
{
description = value.ToString();
}
return description;
}
留言
張貼留言