有一個在我的項目像這樣的枚舉:枚舉綁定組合框中選擇的值設置爲枚舉值
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;
}
並使用以上方法將combobox綁定到myEnum中:
setEnumValues(comboBox, typeof(myEnum));
現在問題是如何設置我的組合框項目或值到特定的一個,如下所示:
combobox.SelectedValue = myEnum.value;
我的項目是在Visual Studio 2010環境中的C#windows項目。
SelectedValue應該可以工作,但myEnum.value必須與Dropdown的value屬性相同。 –
myEnum.value與我的組合框的值屬性相同 –
我的歉意,由於某種原因,我想到了asp.net,而不是winform,這就是爲什麼我想到的是下拉框而不是組合框。 –