问题描述
如何将枚举值绑定到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 })
.ToList< object>();
返回数据;
}
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是一个空字符串。
<$>
p $ p> 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); //将空字段插入到组合框中
}
return data;
}
return null;
}
How to do I bind an enum value to a ComboBox and fill it with an empty field using Linq? I have tried:
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;
}
But I don't know how to insert the empty field into the combobox, however Key is null and Value is an empty string. Can anyone explain what I am missing?
Try this,
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;
}
这篇关于如何绑定枚举到组合框与空字段在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!