如何使用Linq将枚举值绑定到ComboBox并用空字段填充它?我试过:
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是空字符串。有人能解释一下我缺了什么吗?
试试这个,
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;
}