如何将枚举值绑定到ComboBox并使用Linq用空字段填充它?我试过了:
public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
{
if (type.IsEnum)
{
if (fillEmptyField)
{
var data = Enum.GetValues(type)
.Cast<Enum>()
.Select(E => new { Key = (object)Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
.ToList<object>();
return data;
}
else
{
return Enum.GetValues(type)
.Cast<Enum>()
.Select(E => new { Key = Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
.ToList<object>();
}
}
return null;
}
但我不知道如何将空字段插入组合框,但Key为null,Value为空字符串。谁能解释我错过的东西?
答案 0 :(得分:2)
试试这个,
public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
{
if (type.IsEnum)
{
var data = Enum.GetValues(type).Cast<Enum>()
.Select(E => new { Key = (object)Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
.ToList<object>();
var emptyObject = new {Key = default(object), Value = ""};
if (fillEmptyField)
{
data.Insert(0, emptyObject); // insert the empty field into the combobox
}
return data;
}
return null;
}