[英]How to bind Enum to combobox with empty field in C#
如何將枚舉值綁定到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為空字符串。 誰能解釋我所缺少的嗎?
嘗試這個,
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.