我的项目中有一个这样的枚举:
public enum UserFrienlyEnum
{
[Description("it need spec training")]
SPECIAL_TRAINING = 1,
[Description("it need normal training")]
NORMAL_TRAINING = 2,
[Description("it need simple training")]
SIMPLE_TRAINING = 3
}
我使用此方法将此枚举绑定到组合框:
public static void setEnumValues(ComboBox cxbx, Type typ)
{
if (!typ.IsEnum)
{
throw new ArgumentException("Only Enum types can be set");
}
List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
foreach (int i in Enum.GetValues(typ))
{
string name = Enum.GetName(typ, i);
string desc = name;
FieldInfo fi = typ.GetField(name);
// Get description for enum element
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
string s = attributes[0].Description;
if (!string.IsNullOrEmpty(s))
{
desc = s;
}
}
list.Add(new KeyValuePair<string, int>(desc, i));
}
// NOTE: It is very important that DisplayMember and ValueMember are set before DataSource.
// If you do, this works fine, and the SelectedValue of the ComboBox will be an int
// version of the Enum.
// If you don't, it will be a KeyValuePair.
cxbx.DisplayMember = "Key";
cxbx.ValueMember = "Value";
cxbx.DataSource = list;
}
并使用上述方法以这种方式将组合框绑定到 myEnum:
setEnumValues(comboBox, typeof(myEnum));
现在的问题是如何将我的组合框项目或值设置为特定的,如下所示:
combobox.SelectedValue = myEnum.value;
我的项目是 Visual Studio 2010 环境中的 C# windows 项目。